0

我想分配位于 gridview 控件内的下拉列表的数据源。但是当我执行以下代码时,我得到了 NullReferenceException。

Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Try
            Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
            Dim Query As String = "select Course from Courses"
            Dim Command As SqlCommand
            Command = New SqlCommand(Query, Connection)
            Dim Da As New SqlDataAdapter(Command)
            Dim Ds As New DataSet()
            Connection.Close()
            Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
            Da.Fill(Ds)
            ddlCourse.DataSource = Ds    //Exception is here
            ddlCourse.DataTextField = "Course"
            ddlCourse.DataValueField = "Id"
            ddlCourse.DataBind()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End If
End Sub
4

2 回答 2

0

您在填充数据集之前关闭连接,并且您还没有打开连接,因此首先打开连接然后填充数据集,然后您可以关闭连接。

Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
    Try
        Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
        Dim Query As String = "select Course from Courses"
        Dim Command As SqlCommand
        Command = New SqlCommand(Query, Connection)
        Dim Da As New SqlDataAdapter(Command)
        Dim Ds As New DataSet()
        Connection.Open()
        Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
        Da.Fill(Ds)
        ddlCourse.DataSource = Ds    //Exception is here
        ddlCourse.DataTextField = "Course"
        ddlCourse.DataValueField = "Id"
        ddlCourse.DataBind()

    Catch ex As Exception
        MsgBox(ex.ToString)
    Finally
        Connection.Close()
    End Try

End If
End Sub

编辑:添加这一行并运行

   If (ds.Tables.Count > 0) Then

    //your binding code....

  Else

     MsgBox(ex.ToString)

  End If

以供参考

关联

于 2013-01-16T05:22:54.943 回答
0

确保您的下拉列表位于 HTML 代码网格的 ItemTemplate 部分,您可能仅在编辑部分中有它..

       <asp:TemplateField HeaderText="Course">
            <EditItemTemplate>
                     <asp:DropDownList ID="ddlCourse" runat="server">
                    </asp:DropDownList>
            </EditItemTemplate>
            <ItemTemplate>
                 <asp:DropDownList ID="ddlCourse" runat="server">
                    </asp:DropDownList>
                <asp:Label ID="lblCourse" runat="server"  />
            </ItemTemplate>
     </asp:TemplateField>
于 2017-12-13T22:46:36.187 回答