2011-06-13 60 views
1

我需要在DataGridView中獲取ComboBox的選定值。我有它的部分工作,但我得到一個空引用異常如果我更改網格中的另一個組合框。這裏是我的代碼:Get DataGridViewComboboxColumn SelectedValue(VB.Net)

Private Sub dgvSampleList_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles dgvSampleList.EditingControlShowing 
    Dim comboBox As ComboBox = CType(e.Control, ComboBox) 

    If (comboBox IsNot Nothing) Then 
     'Remove an existing event-handler 
     RemoveHandler comboBox.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged) 

     'Add the event handler. 
     AddHandler comboBox.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged) 
    End If 
End Sub 

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) 
    Dim comboBox As ComboBox = CType(sender, ComboBox) 
    'Display selected value 
    MsgBox("ProgramID: " & comboBox.SelectedValue.ToString) 
End Sub 

也能正常工作的第一次組合框改變,但是如果另一組合框改變產生一個空引用異常。任何想法爲什麼發生這種情況?注意:我在MSDN的討論表單中發現了大部分代碼。

謝謝!

彼得

回答

1

嘗試檢查comboBox.SelectedItem.ToString代替comboBox.SelectedValue.ToString

希望有所幫助的。

0

我有同樣的問題。通過對代碼進行細微更改而排序。

聲明一個全局變量

Dim comboBoxCol As New DataGridViewComboBoxColumn 
Dim gol As Integer = 0 



Dim comboBox As ComboBox 
    Private Sub dgvSampleList_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles DGVItems.EditingControlShowing 
     comboBox = CType(e.Control, ComboBox) 

     If (comboBox IsNot Nothing) Then 

      'Add the event handler. 
      AddHandler comboBox.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged) 
      gol = 1 
      'AddHandler comboBox.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectedIndexChanged) 
     End If 
    End Sub 

    Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) 
     comboBox = CType(sender, ComboBox) 
     If gol = 1 Then 
      Dim item As String = comboBox.Text 
      MsgBox(item) 
      gol = 0 
     End If 
    End Sub 
2

這是最好的避免全局變量時,他們是不必要的。

你只需要測試組合框是否試圖訪問的comboBox一個屬性之前什麼:

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) 
    Dim comboBox As ComboBox = CType(sender, ComboBox) 
    'Display selected value 
    If comboBox IsNot Nothing Then 
     MsgBox("ProgramID: " & comboBox.SelectedValue.ToString) 
    End If 
End Sub 

在我看來,當comboBox從舊的值設置爲新的值,即這個SelectedIndexChanged事件被新老組合框和新組合框調用。我懷疑,當它被調用舊的comboBox時,發件人爲null/Nothing,因爲它的值正在改變。也許。但不管發生了什麼,null都是null。在嘗試訪問它的任何屬性之前,只需測試它是否爲空。

相關問題