Getting Selected Items from a ListBox

  • Thread starter Thread starter mzam
  • Start date Start date
M

mzam

Hello everyone,

I have the following ListBox that I populate from a DataView and do the
Databinding as follows:

myDataView = new DataView(myDataSet.myDataTable);

myListbox.DataSource = myDataView;
myListbox.ValueMember = "ID";
myListbox.DisplayMember= "Name";
myListbox.DataBindings.Add("SelectedValue",
myDataSet.myOtherDataTable,"SomeID");

The ListBox is set to multiselect.

The questions is how do I get the values the user has selected in the
ListBox. I do not want to get the DisplayMember but the ValueMembers since I
will be using this ids later in the code.

Cheers!

MZam
 
In your case each item in the listbox is of type DataRowView. This means you
can extract the selected items using the following code:

foreach (DataRowView viewRow in myListbox.SelectedItems)
{
DataRow row = viewRow.Row;
// Retrieve data from DataRow
// ...
}

Regards, Jakob.
 
Hi MZam,

I fear you have to do it the hard way.
ListBox.SelectedObjectCollection soc = listBox1.SelectedItems;

ArrayList IDList = new ArrayList();

foreach(MyObject mo in soc)
{
IDList.Add(mo.ID);
}

Assuming you fill the listbox with MyObjects that have an ID property.
Change names and array types as needed.
 
Thanks a lot Jakob, that did it.

mzam

Jakob Christensen said:
In your case each item in the listbox is of type DataRowView. This means you
can extract the selected items using the following code:

foreach (DataRowView viewRow in myListbox.SelectedItems)
{
DataRow row = viewRow.Row;
// Retrieve data from DataRow
// ...
}

Regards, Jakob.
 
Back
Top