2013-01-16 63 views
0

我想要指定gridview控件內的下拉列表的數據源。但是當我執行下面的代碼時,我得到NullReferenceException。將數據集分配爲下拉列表的數據源時出現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

您填充數據集之前關閉連接,你也沒有打開的連接,從而第一次打開連接,然後填充數據集後,您可以關閉連接。

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 

僅供參考

Link

+0

我試過了。但是同樣的例外。我在課程領域有5個項目,我會得到5個錯誤消息框。 – sujeesh

+0

您是否檢查了我在答案中添加的鏈接,其中有與您的問題相關的完整示例。 – Meherzad

+0

嘗試ddlCourse.DataSource = Ds.Tables [0];對於例外行 – Meherzad

0

確保您的下拉是在網格的ItemTemplate中部分HTML代碼,你可能只在編輯部分有..

 <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> 
相關問題