Wednesday, 28 June 2017

Convert DataTable Rows into Columns in Asp.Net

In this post, I will explain How to Convert DataTable Rows into Columns (Transpose DataTable) using C# in Asp.Net application.

To explain this, I have taken below example. This example uses a DataTable with four rows and three columns as shown in image 1 and after the button click, it will call a method GenerateRowsToColumnsTable(). This Method returns a DataTable with five columns and 2 rows as shown in image 2.

Convert DataTable Rows into Columns
Image 1
  
Convert DataTable Rows into Columns
Image 2

 HTML Code :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestApplication.WebForm1" %>

<!DOCTYPE html>

<html lang="">
<head runat="server">
    <title>Convert DataTable Rows into Columns (Transpose DataTable)</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table width="60%" align="center">
                <tr>
                    <td style=" vertical-align: middle; text-align: center;">
                        <h2>Convert DataTable From Rows To Columns(Transpose DataTable)</h2>
                    </td>
                </tr>
               <tr>
                    <td style="color: blueviolet; vertical-align: middle; text-align: left;">
                        <h3 id="header" runat="server"></h3>
                    </td>
                </tr>
                 <tr>
                    <td width="100%" align="center" valign="top">
                        <asp:DataGrid ID="dgView" runat="server"
                            Width="100%" HorizontalAlign="Center" CellPadding="4" ForeColor="#333333" GridLines="Both">
                            <AlternatingItemStyle BackColor="White" />
                            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                            <ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />
                            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                            <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        </asp:DataGrid>
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:Button ID="btnRowsToColumns" runat="server" Text="Convert Rows To Columns" OnClick="btnRowsToColumns_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


C# Code :

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestApplication
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                header.InnerText = "Data Table before Transpose :";
                BindGrid(CreateDataTable());
            }
        }

        protected void btnRowsToColumns_Click(object sender, EventArgs e)
        {
            header.InnerText = "Data Table after Transpose :";
            DataTable MainTable = CreateDataTable();  // Table in Figure 1
            BindGrid(GenerateRowsToColumnsTable(MainTable));
            btnRowsToColumns.Visible = false;
        }

        private void BindGrid(DataTable tbl)
        {
            dgView.DataSource = tbl;
            dgView.DataBind();
        }

        private DataTable CreateDataTable()
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("Column1", typeof(string));
            tbl.Columns.Add("Column2", typeof(string));
            tbl.Columns.Add("Column3", typeof(string));

            tbl.Rows.Add("Row1", "RC12", "RC13");
            tbl.Rows.Add("Row2", "RC22", "RC23");
            tbl.Rows.Add("Row3", "RC32", "RC33");
            tbl.Rows.Add("Row4", "RC42", "RC43");
            return tbl;
        }

        private DataTable GenerateRowsToColumnsTable(DataTable MainTable)
        {
            DataTable OutputTable = new DataTable();

            // Add columns by looping rows
            // Header row's first column is same as in MainTable
            OutputTable.Columns.Add(MainTable.Columns[0].ColumnName.ToString());

            // Header row's second column onwards, 'MainTable's first column taken
            foreach (DataRow inRow in MainTable.Rows)
            {
                string newColName = inRow[0].ToString();
                OutputTable.Columns.Add(newColName);
            }

            // Add rows by looping columns       
            for (int rCount = 1; rCount <= MainTable.Columns.Count - 1; rCount++)
            {
                DataRow newRow = OutputTable.NewRow();

                // First column is MainTable's Header row's second column
                newRow[0] = MainTable.Columns[rCount].ColumnName.ToString();
                for (int cCount = 0; cCount <= MainTable.Rows.Count - 1; cCount++)
                {
                    string colValue = MainTable.Rows[cCount][rCount].ToString();
                    newRow[cCount + 1] = colValue;
                }
                OutputTable.Rows.Add(newRow);
            }

            return OutputTable;
        }
    }

}

0 comments:

Post a Comment

Please do not enter any spam link in the message box.