Listbox ClearSelected method keeps selected items
I have several winforms list controls that I host in a custom control. The behavior I want in this user control is that I only want one of the lists to have a selected item at a time.
So, if I have an item in Listbox1 and I click an item in listbox2, you should automatically disable all items.
I 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 store the names of the lists in a dictionary. (The number of lists is dynamic). The listBoxName in this example is a list that was just clicked to prevent this code from clearing the selection in that box.
The behavior I get when I run this code is very unexpected. Let's say I have 3 lists ... listbox1, listbox2 and listbox3. Let's say that item3 is currently selected in listbox2. If I click item 4 of listbox1, the end result is that item 4 is selected in listbox1 (as expected), but item 1 is selected in listbox2.
In short, a listBox that previously had an item selection still has 1 item selected, rather than being cleared of selection.
I issued debug.print listBox.SelectedItems.Count right after calling ClearSelection method and of course it said 1 item was selected.
Any thoughts on how to do this or fix my code?
EDIT: BTW, I am binding a list to collections of business objects.
source to share
I ran a quick example with two lists and got this method:
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 fire up all the list boxes by calling the ClearSelected method and then reselect the one that raised the event. Don't run this code on the .SelectedIndex event, which will lead you to an endless loop that will quickly crash.
source to share