将列表转换为表并绑定到gridview

时间:2015-05-20 04:42:12

标签: asp.net vb.net gridview

我有一个包含名称和创建日期

的字段的listitem
        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()

绑定到boundfield

   <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" />

1 个答案:

答案 0 :(得分:1)

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

创建DataTable

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 DataSource

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

使用控件绑定DataTable列

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