获取DataGridViewComboboxColumn SelectedValue(VB.Net)

时间:2011-06-13 04:29:35

标签: vb.net reference null selectedvalue datagridviewcombobox

我需要在DataGridView中获取ComboBox的选定值。我有部分工作,但如果我在网格中更改另一个ComboBox,我会得到 Null引用异常。这是我的代码:

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

这在第一次更改ComboBox时工作正常,但如果另一个ComboBox发生更改,则会生成Null Reference Exception。任何想法为什么会这样?注意:我在MSDN的讨论表中找到了大部分此代码。

谢谢!

彼得

3 个答案:

答案 0 :(得分:2)

最好在不必要时避免使用全局变量。

在尝试访问comboBox的属性之前,您只需要测试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都是null。在尝试访问其任何属性之前,请测试它是否为空。

答案 1 :(得分:1)

尝试检查comboBox.SelectedItem.ToString而不是comboBox.SelectedValue.ToString

希望有所帮助。

答案 2 :(得分: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