How do I select all items in a listbox on checkbox checked?
I have seen a number of (similar) answers all which does logically the same thing, and I was baffled why yet they all dont work for me. The key is setting listbox's SelectionMode
to SelectionMode.MultiSimple
. It doesn't work with SelectionMode.MultiExtended
. Considering to select multiple items in a listbox, you will have selection mode set to multiple mode, and mostly people go for the conventional MultiExtended
style, this answer should help a lot. And ya not a foreach
, but for
.
You should actually do this:
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
lb.SetSelected(i, true);
lb.SelectionMode = //back to what you want
OR
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
lb.SelectedIndices.Add(i);
lb.SelectionMode = //back to what you want
The fact is that ListBox.Items
is a plain object collection and returns plain untyped objects, which cannot be multi-selected (by default).
If you want to multi-select all items, then this will work:
for (int i = 0; i < myListBox.Items.Count;i++)
{
myListBox.SetSelected(i, true);
}