具有数据绑定SelectedItem的ComboBox不会立即更新

时间:2013-06-19 09:21:04

标签: .net vb.net datagridview combobox

在我的表单上,我有一个带有一些DataGridViewComboBoxColumns的DataGridView和一些ComboBox。 DataGridView绑定到BindingSource,并且每个ComboBoxes的SelectedItem属性都绑定到DataGridView中的相应列。 DataGridViewComboBoxColumns和ComboBoxes对具有相同的DataSource项目。

预期的行为是,当我更改网格中的行时,ComboBox应该反映相应列和新选择的行的值。会发生什么是ComboBoxes根据先前选择的行(即后退一步)而改变,导致新选择的行的DataGridViewComboBoxColumns成为最后一行的克隆。

我在其他这样的对上有相同的功能,区别在于他们的DataSource绑定到数据库,而是使用SelectedValue属性。

1 个答案:

答案 0 :(得分:1)

使用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方法应该以相同的方式工作(如果我错了,请纠正我!)。

相关问题