Asp.net 将数据集指定为dropdownlist的数据源时出现NullReferenceException
我想分配gridview控件中dropdownlist的数据源。但是当我执行下面的代码时,我得到了NullReferenceExceptionAsp.net 将数据集指定为dropdownlist的数据源时出现NullReferenceException,asp.net,vb.net,Asp.net,Vb.net,我想分配gridview控件中dropdownlist的数据源。但是当我执行下面的代码时,我得到了NullReferenceException Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then Try Dim Con
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
在填充数据集之前要关闭连接,而且还没有打开连接,因此请先打开连接,然后填充数据集,然后才能关闭连接
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
供参考
确保您的下拉列表位于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>
我试过这个。但在那一行也有同样的例外。我的课程字段中有5个项目,我将得到5个错误消息框。您是否检查了我在答案中添加的链接?有与您的问题相关的完整示例。请尝试ddlCourse.DataSource=Ds.Tables[0];对于例外行,我尝试了链接到@Meherzad。从昨天开始,我就一直这样,我访问了最多的网站,但这是一个奇怪的问题。我也使用了Ds.Tables(0)。但结果是一样的。尝试调试代码检查数据集是否包含any表在这里您可以看到示例或查看我编辑的代码