分层列表框,字典为数据源

时间:2013-04-19 12:21:39

标签: vb.net dictionary hierarchical

我有一个以下设置的ditionary:  字典(String,List(MyObject)

我已经覆盖了MyObject.toString以显示一些不错的东西。

我想创建两个列表框(仅用于显示目的,因此字典不需要更改)。一个包含密钥,另一个包含所选密钥的MyObjects(值)列表。

我尝试了以下但是这给了我两次相同的东西:

Dim bs As BindingSource = New BindingSource(dict,Nothing)
    ListBox1.DataSource = bs
    ListBox1.DisplayMember = "Key"
    ListBox2.DataSource = bs
    ListBox2.DisplayMember = "Value"

任何人都知道如何解决这个问题?

非常感谢。

1 个答案:

答案 0 :(得分:1)

你需要为第一个列表框定义一个事件处理程序(可能是`SelectedIndexChanged')

例如:

 Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    ListBox2.DataSource = New BindingSource(CType(ListBox1.SelectedItem, KeyValuePair(Of String, myObject())).Value, Nothing)
End Sub

我在测试时将通用List更改为数组,这是我用来测试的代码:

Dim dict As New Dictionary(Of String, Object())

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    ListBox2.DataSource = New BindingSource(CType(ListBox1.SelectedItem, KeyValuePair(Of String, Object())).Value, Nothing)
End Sub

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    For j As Integer = 1 To 5
        Dim MyList As New List(Of Object)
        For i As Integer = 1 To 5
            MyList.Add(New With {.Index = i, .Pretty = String.Format("Collection {0} DisplayValue {1} ", j, i)})
        Next
        dict.Add(CStr(j), MyList.ToArray)
    Next

    Dim bs As BindingSource = New BindingSource(dict, Nothing)
    ListBox1.DataSource = bs
    ListBox1.DisplayMember = "Key"

End Sub