views:

339

answers:

1

Hello,

I have several winforms listbox controls I am hosting in a user control. The behavior I want in this user control is that I only want ONE of the listboxes to have a selected item at a time.

So if I have an item in Listbox1 selected and I click an item in listbox2 listbox one should be automatically have all items deselected.

I have tried to accomplish this with the following code:

   dim listBox as listbox
   For Each listName As String In _listboxes.Keys
        If listName <> listboxName Then
            listbox = me.controls(listName)
            listbox.ClearSelected()
        End If
    Next

I am storing the names of the listboxes in a dictionary. (The number of listboxes is dynamic). listBoxName in this example is the listbox that was just click so this code avoids clearing the selection in that box.

The behaviour I get when I run this code is very unexpected. Lets say I have 3 listboxes...listbox1, listbox2, and listbox3. Let's say that item3 in listbox2 is currently selected. If I click item 4 of listbox1 then the end result of this is that item four in listbox1 is selected (as expected) but listbox2 has item 1 selected.

In short, the listBox that previously had an item select still has item 1 selected rather than being cleared of selections.

I emitted a debug.print listBox.SelectedItems.Count immediately after the ClearSelection method call and sure enough it says that 1 items is selected.

Any thoughts on how to do this or fix my code?

Seth

EDIT: BTW, I am binding the listboxes to business object collections.

A: 

I ran a quick example with 2 listboxes and got this method to work:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles ListBox1.Click, ListBox2.Click
    Dim lbx As ListBox = CType(sender, ListBox)
    Dim i As Integer = lbx.SelectedIndex
    ListBox1.ClearSelected()
    ListBox2.ClearSelected()

    lbx.SelectedIndex = i

End Sub

Just loop through all your list boxes, calling the ClearSelected method, then re-select the one that triggered the event. Don't run this code in the .SelectedIndex event, that will get you into an infinite loop that will quickly cause a crash.

Stewbob