【问题标题】:convert list to table and bind to gridview将列表转换为表格并绑定到gridview
【发布时间】:2015-05-20 13:24:22
【问题描述】:

我有一个包含名称和创建日期字段的列表项

        Dim files As List(Of ListItem) = New List(Of ListItem)
        For Each filePath As String In filePaths
            files.Add(New ListItem(Path.GetFileName(filePath), filePath))
            files.Add(New ListItem(File.GetCreationTime(filePath), filePath))
        Next
        GridView2.DataSource = files
        GridView2.DataBind()

绑定到边界域

   <asp:BoundField DataField="Text" HeaderText="Report Name" />

第一个 files.add 是 name,第二个是 Creation date 它只显示一列如何将它们转换为 2 列

   <asp:BoundField DataField="Text" HeaderText="Report Name" />
<asp:BoundField DataField="???" HeaderText="Creation Date" />

【问题讨论】:

    标签: asp.net vb.net gridview


    【解决方案1】:

    您需要在此处使用DataTable 而不是ListItem,因为您可能需要绑定两个以上的列。

    创建数据表

    Function GetTable() As DataTable
    {
        // Here we create a DataTable with four columns.
         Dim table As New DataTable
         table.Columns.Add("FileName");
         table.Columns.Add("FileCreationTime");
         For Each filePath As String In filePaths
            table.Rows.Add(Path.GetFileName(filePath), File.GetCreationTime(filePath).ToString())
         Next   
        return table;
    }
    

    将 DataTable 分配给 GridView 数据源

    GridView2.DataSource = GetTable()
    GridView2.DataBind()
    

    用控件绑定 DataTable 列

    <asp:BoundField DataField="FileName" HeaderText="Report Name" />
    <asp:BoundField DataField="FileCreationTime" HeaderText="Creation Date" />
    

    【讨论】:

    • 看起来你的代码可以工作,你能转换成 Vb.Net 吗?我尝试使用网站进行转换,但 Typedecl 出现错误
    • 我已经尝试过了,但我想我错过了 Table 声明。你能试试看,如果还有什么需要改变的,请告诉我。您对转换为 VB.net 的建议将是一个加分项!
    • 好的,我用它作为这样的函数 Function GetTable() As DataTable 替换 static DataTable GetTable() 并且你的代码就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2014-07-29
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多