获取DataGridViewComboboxColumn SelectedValue(VB.Net)

前端之家收集整理的这篇文章主要介绍了获取DataGridViewComboboxColumn SelectedValue(VB.Net)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在DataGridView中获取ComboBox的选定值.我有部分工作,但如果我在网格中更改另一个ComboBox,我会得到一个Null Reference Exception.这是我的代码
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的讨论表中找到了大部分此代码.

谢谢!

彼得

当不必要时,最好避免使用全局变量.

在尝试访问comboBox属性之前,您只需要测试comboBox是否为空:

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object,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.在尝试访问其任何属性之前,只测试它不是null.

原文链接:https://www.f2er.com/vb/255597.html

猜你在找的VB相关文章