Nicholas Aysen
Nicholas Aysen

Reputation: 580

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.

Upvotes: 1

Views: 5367

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125197

To get list of selected values when the data source is a DataTable, you can use this code:

var selectedValues = listBox1.SelectedItems.Cast<DataRowView>()
                             .Select(dr => (int)(dr[listBox1.ValueMember]))
                             .ToList();

But in general Item of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

If you are looking for a good solution which works with different settings and different data sources, you may find this post helpful. It contains an extension method which returns value of an item. It works like GetItemText method of ListBox.

Upvotes: 1

Nicholas Aysen
Nicholas Aysen

Reputation: 580

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}

Upvotes: 0

Related Questions