0

页面加载:-

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

这是网格视图:-

<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

但是当我调试时它会在下面显示异常 - gvBatches.DataBind()

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.

我不明白这个 id 是什么?我的表中没有这样的列。

4

2 回答 2

0

在您的 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功能

于 2013-01-22T14:55:12.040 回答
0

我建议先设置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")
于 2013-01-22T14:47:21.253 回答