获取 DataGridViewComboboxColumn SelectedValue (VB.Net)
Posted
技术标签:
【中文标题】获取 DataGridViewComboboxColumn SelectedValue (VB.Net)【英文标题】:Get DataGridViewComboboxColumn SelectedValue (VB.Net) 【发布时间】:2011-06-13 04:29:35 【问题描述】:我需要在 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,则会生成空引用异常。任何想法为什么会发生这种情况?注意:我在 MSDN 的讨论表单中找到了大部分代码。
谢谢!
彼得
【问题讨论】:
【参考方案1】:全局变量在不必要时最好避免使用。
您只需要在尝试访问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/Nothing,因为它的值正在改变。也许。但无论发生什么,空值就是空值。在尝试访问它的任何属性之前,只需测试它不为空即可。
【讨论】:
【参考方案2】:尝试检查comboBox.SelectedItem.ToString
而不是comboBox.SelectedValue.ToString
希望对您有所帮助。
【讨论】:
【参考方案3】:我也有同样的问题。通过对代码进行小的更改进行整理。
声明一个全局变量
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
【讨论】:
以上是关于获取 DataGridViewComboboxColumn SelectedValue (VB.Net)的主要内容,如果未能解决你的问题,请参考以下文章