页面加载:-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Page.Title = "Batches - " & Website
BindBatches()
Catch ex As Exception
Logger.WriteError("Error in Page_Load of Batches/batches.aspx", ex)
End Try
End Sub
此子例程将batch_name绑定到网格视图
Protected Sub BindBatches()
Try
Dim ds As New DataSet()
ds = Dal.ExecuteDataset("select batch_name from tblBatch")
If Not ds Is Nothing AndAlso ds.Tables(0).Rows.Count > 0 Then
gvBatches.DataSource = ds
gvBatches.DataBind()
gvBatches.Visible = True
Else
gvBatches.Visible = False
End If
Catch ex As Exception
Logger.WriteError("Error in BindBatches of Batches/batches.aspx", ex)
End Try
End Sub
这是gridview:-
<asp:GridView ID="gvBatches" runat="server">
<Columns>
<asp:TemplateField HeaderText="Batch Name">
<HeaderStyle Width="40px"></HeaderStyle>
<ItemTemplate>
<asp:Label ID="lblBatchName" runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
和绑定事件:-
Protected Sub gvBatches_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBatches.RowDataBound
If e.Row.RowType = ListItemType.Item Or e.Row.RowType = ListItemType.AlternatingItem Then
Dim batchName As Label = e.Row.FindControl("lblBatchName")
batchName.Text = e.Row.DataItem("batch_name")
End If
End Sub
但是当我调试时,它会显示下面的异常- gvbatch . databind ()
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.
我不明白这个id是什么?在我的表中没有这样的列
我建议先将OPTION STRICT
设置为on。看到这段代码(DataItem
是一个Object
)甚至会感到痛苦:
batchName.Text = e.Row.DataItem("batch_name")
试着适当地转换它:
Dim row As DataRow = DirectCast(e.Row.DataItem, DataRowView).Row
batchName.Text = row.Field(Of String)("batch_name")
在你的aspx文件中你可以改变你的标签声明为
<asp:Label ID="lblBatchName" runat="server" Text='<%# Eval("batch_name") %>'>
不需要Protected Sub gvBatches_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBatches.RowDataBound
函数