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 に答える