【问题标题】:Convert GridView table to Html Table but Rows should be columns and columns should be Rows将 GridView 表转换为 Html 表,但行应该是列,列应该是行
【发布时间】:2011-10-29 16:42:28
【问题描述】:

我的数据集 ds 中填充了值 直到现在我在 GridView 中显示值。现在我希望所有行应该是列,列应该是行

我有 2 个选项:1 我可以直接将网格转换为列并显示它,或者 2 我可以将 GridView 转换为 html,然后编写循环进行转换。我正在尝试第二个选项,但我不知道该怎么做。以下是我的代码:

For Each dr In dt.Rows
    htmlTable = htmlTable + "<TR>"
    For Each dc In dt.Columns
        htmlTable = htmlTable + "<TD>" + ds.Tables(0).Columns(j).ToString() + ""
        j = j + 1
    Next
    i = i + 1
Next

使用此代码,我仍然可以得到与 GridView 相同的效果。请帮助我将行转换为列,反之亦然。

【问题讨论】:

    标签: asp.net vb.net gridview .net-3.5 html-table


    【解决方案1】:

    看起来您试图从 DataSet 中的 DataTable 编写 HTML 表,翻转行和列。您发布的代码有几个问题,所以我更多地将它用作我的答案的伪代码。

    您得到与 GridView 相同的东西(在行和列方面)的原因是因为您循环遍历每一行,并且在每一行中循环遍历所有列 - 您没有翻转列和行完全没有。

    试试这样的:

    Dim htmlTable As StringBuilder = new StringBuilder()
    Dim numberRows As Integer = ds.Tables(0).Rows.Count - 1
    Dim numberCols As Integer = ds.Tables(0).Columns.Count - 1
    
    htmlTable.Append("<table>")
    
    ' Loop through each column first
    For i As Integer = 0 To numberCols
        htmlTable.Append("<tr>")
    
        ' Now loop through each row, getting the current columns value
        ' from each row
        For j As Integer = 0 To numberRows
            htmlTable.Append("<td>")
            htmlTable.Append(ds.Tables(0).Rows(j)(i))
            htmlTable.Append("</td>")
        Next
    
        htmlTable.Append("</tr>")
    Next
    
    htmlTable.Append("</table>")
    
    ' To get the value of the StringBuilder, call ToString()
    Dim resultHtml = htmlTable.ToString()
    

    例如,如果您有这样的表:

    col1 col2 col3

    a b c

    d e f

    g h 我

    jkl

    结果是:

    a d g j

    b e h k

    c f i l

    【讨论】:

    • 而不是 ds.tables[0] 中的方括号 [] ...在 vb.net 中用圆括号()替换
    • 是的 - 你是对的。对此感到抱歉 - 我主要处理 C#,所以即使是 VB.NET,我偶尔也会陷入这种语法。为了完整起见,我将对其进行编辑。很好的收获。
    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2013-08-22
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多