views:

529

answers:

2

I am BATTLING to get the selected values (please note VALUES not TEXT) from a Winforms Listbox that has multi-select enabled and has been bound to a database table getting the Name (as DisplayMember) and ID (as ValueMember) - I need the ID of the selected items.

The listbox control has properties for SelectedValue to get one of the selected items values, but not for all selected items values.

The SelectedItems property returns a Listbox.SelectedObjectCollection from which I cannot seem to extract the VALUES of the items.

Please help! Thanks.

+3  A: 

SelectedItems is what you want.

SelectedItem and SelectedValue are only different when you set DisplayMember and ValueMember. I don't think this is supported for Multi-select.

What type of Items are you adding to the listbox?

Henk Holterman
Apologies, I have updated the initial question - I have bound the control to a database table with Name as DisplayMember and ID as ValueMember. I want to get the selected items IDs
Jimbo
See @Steve Dignans answer, you probably need to cast to CustomerRow or something.
Henk Holterman
+2  A: 

Try casting each object in the collection to the desired type. For example, if my items are of type Customer, I could do something like this...

var selected = listBox1.SelectedItems;

foreach ( var item in selected )
{
    var singleCustomer = (Customer)item;
}

Now you can get any property you want from the Customer.

This is just a trivial example, but I'm sure you can apply the concept to your problem.

UPDATE (after question was updated to indicate the Listbox is bound to table):

If you're bound to a DataTable, you could try something like this (again, trivial but relevent):

var selected = listBox1.SelectedItems;

foreach ( var item in selected )
{
    var itemArray = ( (DataRowView)item ).Row.ItemArray;

    var name = itemArray[0];
    var id = itemArray[1];
}
Steve Dignan
This is the way I've done it when I add things manually, but I don't know how it works with bound controls.
ho1