通过使用 SelectedValue 属性而不是 SelectedItem 解决。为了能够使用此属性,必须设置 ComboBox 的 .ValueMember,因此我必须使用具有属性的对象,而不是 ComboBox 项列表中的简单字符串。我创建了一个类:
Public Class ComboItem
Private cText As String
Private cValue As Object
Public Sub New(ByVal text As String, ByVal value As Object)
Me.cText = text
Me.cValue = value
End Sub
Public Sub New(ByVal text As String)
Me.cText = text
Me.cValue = text
End Sub
Public Property value() As Object
Get
Return cValue
End Get
Set(ByVal value As Object)
cValue = value
End Set
End Property
Public Property text() As String
Get
Return cText
End Get
Set(ByVal value As String)
cText = value
End Set
End Property
End Class
并像这样设置绑定:
Dim itemList As List(Of ComboItem) = New List(Of ComboItem) From {New ComboItem("", DBNull.Value),
New ComboItem("Item 1"),
New ComboItem("Item 2")}
Dim bindingSource As BindingSource = New BindingSource
bindingSource.DataSource = itemList
ComboBox1.DataSource = bindingSource
ComboBox1.DisplayMember = "text"
ComboBox1.ValueMember = "value"
dataGridViewTextBoxColumn.DataSource = bindingSource
dataGridViewTextBoxColumn.DisplayMember = "text"
dataGridViewTextBoxColumn.ValueMember = "value"
我从设计器中设置了 SelectedValue 绑定,但代码看起来像这样:
ComboBox1.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", dataGridViewBindingSource, "ColumnName", True))
这个答案实际上更像是一种解决方法,因为据我所知, SelectedItem 方法应该以相同的方式工作(如果我错了,请纠正我!)。