Mohamed Mohamed - 1 year ago 92
C# Question

How to retrieve selected values for multiple selected items in a ListBox, bound to a database?

I'm populating a ListBox in a WinForms application, this way:

listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";

how to retrieve the selected Ids when I'm setting the

I want to do a
loop on them, like this:

foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
int id = int.Parse(itemId);
// . . .

Answer Source

Since you know the type of items, you can use such code:

var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();

Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:

var selectedValues = listBox1.SelectedItms.Cast<object>()
                             .Select(x => listBox1.GetItemValue(x)).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download