Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting multiple Listbox items through code

Tags:

c#

listbox

Hi there I have searched for a while now and can't seem to find a solution to my problem, I have tried multiple methods to select multiple items in my listbox through code however none have worked, The best result I got was 1 selected item in my listbox.

Basically I want to select multiple items of the same value.

below is my code, sorry if I seem newbie but I am new to programming and still learning basic stuff.

 foreach (string p in listBox1.Items)
 {
           if (p == searchstring) 
           {
                 index = listBox1.Items.IndexOf(p);
                 listBox1.SetSelected(index,true);

           }
 }

So as you can see I am trying to tell the program to loop through all the items in my listbox, and for every item that equals "searchstring" get the index and set it as selected.

However all this code does is select the first item in the list that equals "searchstring" makes it selected and stops, it doesn't iterate through all the "searchstring" items.

like image 632
user1784219 Avatar asked Oct 29 '12 22:10

user1784219


People also ask

How do I select multiple items in ListBox?

Choose Multiple Items from Listbox On the worksheet, click on a cell that has a drop down list. The VBA listbox pops up automatically, and shows all the choices from the cell's drop down list. Add a check mark to one or more of the items in the list box. When you're finished selecting items, click the OK button.

How do I get all items selected in ListBox?

You can use the ListBox. GetSelectedIndices method and loop over the results, then access each one via the items collection. Alternately, you can loop through all the items and check their Selected property.

Which property ListBox is set to allow users to select multiple items?

The SelectionMode property enables you to determine how many items in the ListBox a user can select at one time and how the user can make multiple-selections.


1 Answers

As suggested in the comment, you should set SelectionMode to either MulitSimple or MultiExpanded depending on your needs, but you also need to use for or while loop instead offoreach, because foreach loop doesn't allow the collection to be changed during iterations. Therefore, even setting this Property won't make your code run and you will get the exception. Try this:

for(int i = 0; i<listBox1.Items.Count;i++)
{
     string p = listBox1.Items[i].ToString();
     if (p == searchstring)
     {
          listBox1.SetSelected(i, true);

     }
}

You can set SelectionMode either in the Properties window when using designer or in, for instance, constructor of your Form using this code:

listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
like image 166
Nikola Davidovic Avatar answered Oct 13 '22 10:10

Nikola Davidovic