65.9K
CodeProject 正在变化。 阅读更多。
Home

使用C#转置DataTable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (24投票s)

2009年11月21日

CPOL

1分钟阅读

viewsIcon

182634

使用 C# 将 DataTable 的行转换为列,反之亦然。

引言

本文档将帮助您使用 C# 代码在 ASP.NET Web 应用程序(也可用于 Windows 窗体)中转换(将行转换为列,将列转换为行)DataTable

背景

本文档使用 .NET Framework 3.5,但由于 DataTable 适用于所有版本,因此可以在任何版本中使用。读者应熟悉基本的 ASP.NET、C# 和 DataTable 概念才能理解本文档。

Using the Code

此代码使用一个包含四个列和三行的 DataTable,如下所示。调用 GenerateTransposedTable 方法后,将得到如下第二个表格所示的输出。

这可以在 DataGrid 控件(Windows 和 Web 应用程序中均可)中使用。只需单击一下,就可以转换表格。这可能有助于我们的大多数报告功能。

这里,我将其用于 ASP.NET 网页。

原始表格

状态 阶段 I 阶段 II 阶段 III
未开始 100 200 300
部分完成 101 201 301
成功完成 102 202 302
已阻塞 103 203 303
有条件完成 104 204 304
无法继续 105 205 305

转换后的表格

状态 未开始 部分完成 成功完成 已阻塞 有条件完成 无法继续
阶段 I 100 101 102 103 104 105
阶段 II 200 201 202 203 204 205
阶段 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>

这是代码

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;
}

结论

您会注意到原始报告已转换为(行转换为列,列转换为行),如图所示。

历史

  • 2009 年 11 月 21 日:初始发布
  • 2010 年 2 月 12 日:更新文章 - 添加了背景部分
© . All rights reserved.