【问题标题】:ComboBox with databound SelectedItem is not updated at once带有数据绑定 SelectedItem 的 ComboBox 不会立即更新
【发布时间】:2013-06-15 18:26:20
【问题描述】:

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

预期的行为是,当我更改网格中的行时,组合框应该反映相应列的值和新选择的行。发生的情况是 ComboBoxes 根据先前选择的行(即落后一步)发生变化,导致新选择的行的 DataGridViewComboBoxColumns 是最后一个的克隆。

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

【问题讨论】:

  • 更改网格背后的代码是什么?
  • 通过更改网格中的行,我的意思是当用户在网格中单击或使用键盘向上/向下移动时在 GUI 中
  • 好的,你有那个事件背后的任何代码还是只有属性设置?
  • 不,只有属性设置。我读过有关其他人对 SelectedItem 属性有问题的信息,该属性的行为似乎与预期不符。将尝试另一种方法,用对象而不是字符串填充 ComboBoxes,并改用 SelectedValue 属性。

标签: .net vb.net datagridview combobox


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

【讨论】:

  • gv.Columns[i].DefaultCellStyle.NullValue = "your value" 给出默认值
猜你喜欢
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2011-11-01
  • 2023-04-03
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多