Question

I have a ditionary with following setup: Dictionary(of String, List(of MyObject)

I have overwritten the MyObject.toString to display something decent.

I would like to create two listboxes (only for showing purposes so dictionary does not need to be altered). One contains the key and the other contains the list of the MyObjects (value) of the selected key.

I have tried the following but this gives me the same thing twice:

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

Anyone have an idea how I can fix this?

Much appreciated.

Was it helpful?

Solution

You'll need to define an event handler for the first listbox (probably `SelectedIndexChanged')

For example:

 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

I changed the generic List to an array while I was testing this, here's the code I used to test:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top