我试图在ASP.NET中创建一个动态绑定的GridView。GridView本身我已经在aspx文件中定义了。但是所有的列和行我都需要动态地创建。SQL DataBind对我来说不是一个解决方案,因为我最终需要执行额外的逻辑。
下面是代码。
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
代码如下:
Protected Sub CreateGrid()
Dim table As DataTable = New DataTable
table.Columns.Add(New DataColumn("Name", GetType(BoundField)))
Dim i As Integer = 0
While i < 10
Dim dr As DataRow = table.NewRow()
dr("Name") = i.ToString()
table.AcceptChanges()
i += 1
End While
GridView1.DataSource = table
GridView1.DataBind()
End Sub
你正在创建行,但从未将它们添加到表中。
Protected Sub CreateGrid()
Dim table As New DataTable
table.Columns.Add("Name", GetType(String))
For i = 0 To 9
Dim dr As DataRow = table.NewRow()
dr("Name") = i.ToString()
table.Rows.Add(dr)
Next
table.AcceptChanges()
GridView1.DataSource = table
GridView1.DataBind()
End Sub
我还做了一些其他的改进,没有额外的费用。可能也没有什么好的理由。AcceptChanges
呼叫。