How do I select all items in a listbox on checkbox checked?

SO User picture SO User · Jun 1, 2009 · Viewed 64.7k times · Source

I need to select all items in a ListBox when a CheckBox is clicked. Is it possible to select all items in the ListBox using a single line of code? Or will I have to loop through all items and set selected to true for each one of them?

Answer

Mehdi LAMRANI picture Mehdi LAMRANI · Dec 1, 2010

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);
   }