我想分配一个位于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
答案 0 :(得分: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
供参考
答案 1 :(得分: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>