Listbox selecteditems
-
I have a listbox(default except theat the selectionmode is "multisimple") that I'm populating dynamically through a BindingSource, with the display and value member set to the same column. On loading of the form, I need to set the initial selected value(s) to a previously-stored value. I declare a List called toSelect and fill it with the correct values. My problem is actually taking those values and selecting the correct listbox item(s). What I currently have is:
foreach (string s in toSelect) { if (uxlbSuite.Items.Contains(s)) { uxlbSuite.SelectedItems.Add(s); } }
The problem is that uxlbSuite.Items.Contains(s) always returns false, and the uxlbSuite.SelectedItems.Add(s) doesn't actually do anything if I don't perform the if check. I think I'm accessing the SelectedItems list wrong, but I'm baffled as to the correct way, and advice would be greatly appreciated.
-
I have a listbox(default except theat the selectionmode is "multisimple") that I'm populating dynamically through a BindingSource, with the display and value member set to the same column. On loading of the form, I need to set the initial selected value(s) to a previously-stored value. I declare a List called toSelect and fill it with the correct values. My problem is actually taking those values and selecting the correct listbox item(s). What I currently have is:
foreach (string s in toSelect) { if (uxlbSuite.Items.Contains(s)) { uxlbSuite.SelectedItems.Add(s); } }
The problem is that uxlbSuite.Items.Contains(s) always returns false, and the uxlbSuite.SelectedItems.Add(s) doesn't actually do anything if I don't perform the if check. I think I'm accessing the SelectedItems list wrong, but I'm baffled as to the correct way, and advice would be greatly appreciated.
Hi Drew, to locate an item by its string value you want FindString() or FindStringExact() The SelectedItems collection represents an observed state of the listbox, changing it does not change the listbox state. You want SetSelected(). :)
Luc Pattyn
-
Hi Drew, to locate an item by its string value you want FindString() or FindStringExact() The SelectedItems collection represents an observed state of the listbox, changing it does not change the listbox state. You want SetSelected(). :)
Luc Pattyn
Thanks for the response. What I ended up getting working was looping through the items list (which will never be more than a dozen or so), rather than the List<> of items that needed to select. From that, I could parse the correct object from the associated datarow (by casting it as such) and then compare that to the list of approved items.
uxlbSuite.SelectedItems.Clear(); List objectsToAdd = new List(); foreach (object unit in uxlbSuite.Items) { System.Data.DataRowView Row = unit as System.Data.DataRowView; if (Row != null && toSelect.Contains(Row["ID"].ToString())) { objectsToAdd.Add(unit); } } foreach (object unit in objectsToAdd) { uxlbSuite.SelectedItems.Add(unit); }