Search code examples
c#winformslistboxselecteditemselectedvalue

How to get multiple selected values from listbox C# Windows Application


I am using a Listbox on my windows application. The listbox has a multi-selection option, which users select all the roles the new user will have. My Listbox is bound to a dataset. The table is Roles, with an ID column and Description column. When I bound the listbox, I chose the data source being the dataset, the display member to be the description, the value member being the ID and the selected value being the dataset - roles.frolesidenter image description here

Now when i loop through the listbox's selecteditems, i get only the first item's values etc...

I am trying to assign an int to the current selectedvalue, to get the ID to give to the user.

 int num = 0;
 foreach (var item2 in lstRoles.SelectedItems)
 {
      num = Convert.ToInt32(lstRoles.SelectedValue);
 }

So if I select 3 roles, for instance Administrator, Capturer and Assessor, I only see the Administrator value.

How do I loop and access the next item? I'm not even using

item2 in my code. Could this be utilised?

For instance:

enter image description here

First iteration:

enter image description here

And it just stays on that selected item, never moving to the next item.


Solution

  • solved it

                int num = 0;
                int count = fRoleIDs.Count;
                while (num != count)
                {
                    var item = lstRoles.Items[num] as System.Data.DataRowView;
                    int id = Convert.ToInt32(item.Row.ItemArray[0]);
                    num += 1;
                }
    

    This goes into the listbox's items and according to the index, gets the item as a Row. This then gets me the itemarray, which is ID and Description {0,1}