Click here to Skip to main content
12,241,975 members (49,239 online)
Click here to Skip to main content
Add your own
alternative version

Stats

94.2K views
22 bookmarked
Posted

Transpose a DataTable using C#

, 12 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Transpose DataTable rows into columns and vice versa using C#.

Introduction

This article helps to transpose (convert rows into columns and columns into rows) a DataTable using C# code in an ASP.NET Web application (can be used in Windows Form as well).

Background

This articles uses .NET Framework 3.5, can be used in any version as DataTable is applicable to all. Readers should be familiar with basic ASP.NET, C# & DataTable concepts to understand this article.

Using the Code

This code uses a DataTable with four columns and three rows as shown below. After calling the method GenerateTransposedTable, it will give you the output which is shown in the second table.

This can be used in the DataGrid control (both in Windows and Web applications). Using a single click, we can transpose a table. This may help us in most of the reporting functionalities.

Here, I have used it in an ASP.NET web page.

Actual Table

Status Phase I Phase II Phase III
Not Started 100 200 300
Partially Completed 101 201 301
Successfully Completed 102 202 302
Blocked 103 203 303
Completed with Conditions 104 204 304
Cannot proceed 105 205 305

Transposed Table

Status Not Started Partially Completed Successfully Completed Blocked Completed with Conditions Cannot proceed
Phase I 100 101 102 103 104 105
Phase II 200 201 202 203 204 205
Phase III 300 301 302 303 304 305
<table id="TableTopGrid" 
        style="width: 100%; border-left: darkgray 1px solid;"
        cellspacing="0" cellpadding="0" align="center">                           
    <tr>
    <td style="width:100%; background-color: #66ccff" align="center">
        <asp:Button ID="btnTransposeReport" 
            runat="server" Font-Bold="True" 
            Font-Names="Tahoma"
            Font-Size="8pt" Text="Query" 
            Width="75px" ForeColor="Navy" 
            OnClick="btnTransposeReport_Click" />
    </td>
    </tr>
    <tr>
    <td width="100%" align="center" valign="top">
        <asp:DataGrid ID="GridReport" runat="server"
           Height="100%" Width="100%" HorizontalAlign="Center"
           Font-Size="8pt" EditItemStyle-Wrap="true" 
           Font-Names="Tahoma" PageSize="50"
           AutoGenerateColumns="True" 
           AllowPaging="False" AllowSorting="False" GridLines="Both"
           ShowFooter="False" BackColor="AliceBlue">
        <ItemStyle Height="18px" Width="100%" 
            HorizontalAlign="Center" CssClass="Grid" />
        <HeaderStyle Font-Size="8pt" Font-Names="Tahoma" 
            Font-Bold="False" Width="100%" Height="20px"
            ForeColor="White" BackColor="DimGray" 
            HorizontalAlign="Center" CssClass="Grid" />

        </asp:DataGrid>
       </td>
    </tr>
    <tr>
    <td style="width:100%; background-color:DimGray" align="center">
        &nbsp;
    </td>
    </tr>
</table>

Here is the code:

protected void Page_Load(object sender, EventArgs e)
{        
     if (!IsPostBack)
     {
         GridReport.DataSource = <your datatable>;
         // This is the table I shown in Figure 1.1

         GridReport.DataBind();

         // Your other codes here (if any)
     }
}

protected void btnTransposeReport_Click(object sender, EventArgs e)
{
     DataTable inputTable = <your datatable>;
     // Table shown in Figure 1.1

     DataTable transposedTable = GenerateTransposedTable(inputTable);

     GridReport.DataSource = transposedTable;
     // Table shown in Figure 1.2

     GridReport.DataBind();
}

private DataTable GenerateTransposedTable(DataTable inputTable)
{
     DataTable outputTable = new DataTable();

     // Add columns by looping rows

     // Header row's first column is same as in inputTable
     outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());

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

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

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

     return outputTable;
}

Conclusion

You can notice that the actual report is transposed (rows into columns and columns into rows) as shown in the figure.

History

  • 21st November, 2009: Initial post
  • 12th February, 2010: Updated article - added Background section

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S Satheesh Kumar
Technical Lead
India India
Around 9 years of experience in Microsoft Technologies

You may also be interested in...

Comments and Discussions

 
QuestionThank You ! Pin
MarcusCole09207626-Jan-16 12:03
professionalMarcusCole09207626-Jan-16 12:03 
SuggestionEasy Method to DataTable Transport Pin
Virendra Agarwal10-Aug-12 17:58
memberVirendra Agarwal10-Aug-12 17:58 
GeneralMy vote of 5 Pin
m.varaprasadmca6-Jun-12 3:54
memberm.varaprasadmca6-Jun-12 3:54 
GeneralMy vote of 5 Pin
Prince Antony G24-Jan-12 3:05
memberPrince Antony G24-Jan-12 3:05 
GeneralMy vote of 5 Pin
E$w@r8-Feb-11 18:38
memberE$w@r8-Feb-11 18:38 
GeneralMy vote of 5 Pin
franklinraj2-Dec-10 6:44
memberfranklinraj2-Dec-10 6:44 
GeneralRe: My vote of 5 Pin
S Satheesh Kumar15-Dec-10 12:19
memberS Satheesh Kumar15-Dec-10 12:19 
GeneralThanx Pin
David Cruwys29-Jul-10 16:02
memberDavid Cruwys29-Jul-10 16:02 
GeneralVote of 3: Code is useful Pin
David Cruwys29-Jul-10 16:01
memberDavid Cruwys29-Jul-10 16:01 
GeneralRe: Vote of 3: Code is useful Pin
S Satheesh Kumar2-Aug-10 5:31
memberS Satheesh Kumar2-Aug-10 5:31 
General[My vote of 2] Works only with strings. Cannot work with any other datatype. Pin
Som Shekhar21-Nov-09 8:45
memberSom Shekhar21-Nov-09 8:45 
GeneralMy vote of 1 Pin
Dave Kreskowiak21-Nov-09 7:16
mvpDave Kreskowiak21-Nov-09 7:16 
Questionwouldn't this be better done IN the database? Pin
l a u r e n 21-Nov-09 2:00
member l a u r e n 21-Nov-09 2:00 
AnswerRe: wouldn't this be better done IN the database? Pin
S.Satheesh21-Nov-09 2:28
memberS.Satheesh21-Nov-09 2:28 
GeneralCould do with more detail Pin
Richard MacCutchan21-Nov-09 1:15
memberRichard MacCutchan21-Nov-09 1:15 
GeneralRe: Could do with more detail Pin
S.Satheesh21-Nov-09 2:24
memberS.Satheesh21-Nov-09 2:24 
GeneralRe: Could do with more detail Pin
Richard MacCutchan21-Nov-09 7:27
memberRichard MacCutchan21-Nov-09 7:27 
GeneralMy vote of 1 Pin
digital man21-Nov-09 0:41
memberdigital man21-Nov-09 0:41 
GeneralRe: My vote of 1 Pin
S.Satheesh21-Nov-09 2:26
memberS.Satheesh21-Nov-09 2:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 12 Feb 2010
Article Copyright 2009 by S Satheesh Kumar
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid