0

我知道这是一项简单的任务,但我无法设置ComboBox.SelectedItem。假设我有以下代码....

Class InnerClass
    Public InnerProperty As String
End Class

Class [Class]
    Public [Property] As String
    Public InnerClass As InnerClass
End Class

Private Sub Form_Load(ByVal sender As Object,ByVal e as EventArgs)
    Dim cls as New [Class]
    Dim innerCls as New InnerClass
    Dim list as New BindingList(Of InnerClass)

    list.Add(New InnerClass)
    list.Add(New InnerClass)
    list.Add(New InnerClass)       
    cls.InnerClass=list.Items(2)
    ComboBox1.DataSource=list 
    ComboBox1.DisplayMember="InnerProperty"
    ComboBox1.DisplayValue="InnerProperty"
    ComboBox1.DataBindings.Add("SelectedItem",cls,"InnerClass") 'always displays 1st item
    list.Add(innerCls)
    ComboBox1.SelectedItem=innerCls 'No effect
End Sub

如何使ComboBox1.SelectedItem正确绑定到 [Class].InnerProperty?如何手动设置ComboBox1.SelectedItem ?

4

2 回答 2

1

数据绑定仅适用于属性,而不适用于字段。我添加了 ComboBox ValueMember 属性,并将 DataBinding 更改为使用 SelectedValue 属性。

这是一个重新设计的示例:

Class InnerClass
  Public Property InnerProperty As String
End Class

Class [Class]
  Public Property [Property] As String
  Public Property InnerClass As InnerClass
End Class

Protected Overrides Sub OnLoad(e As EventArgs)
  MyBase.OnLoad(e)

  Dim cls As New [Class]
  Dim innerCls As New InnerClass

  Dim list As New BindingList(Of InnerClass)
  list.Add(New InnerClass With {.InnerProperty = "aaa"})
  list.Add(New InnerClass With {.InnerProperty = "bbb"})
  list.Add(New InnerClass With {.InnerProperty = "ccc"})
  cls.InnerClass = list(2)
  ComboBox1.DisplayMember = "InnerProperty"
  ComboBox1.ValueMember = "InnerProperty"
  ComboBox1.DataSource = list

  Dim bd As New Binding("SelectedValue", cls, "InnerClass.InnerProperty")
  ComboBox1.DataBindings.Add(bd)
End Sub

附带说明一下,请避免创建一个名为“Class”的类和一个名为“Property”的属性。给他们真实姓名。

要使用该类,您必须改用 SelectedItem:

Dim bd As New Binding("SelectedItem", cls, "InnerClass")
于 2013-08-30T15:31:32.067 回答
0

如何手动设置 ComboBox1.SelectedItem?

ComboBox1.SelectedItem = Object

我认为在您的情况下是“bbb - bbb”,因为您对显示和价值成员使用相同的东西。ComboBox1.SelectedValue = "bbb" 更易于阅读和输入。通常操作选定的值或索引对我来说更容易,或者更不容易出错。就像肯怀特说的,虽然你需要表达价值成员才能使用它。

于 2013-08-30T16:09:32.843 回答