I'm trying to get all the selected items ValueMember from a ListBox with C#.
For ex.:
I've a list like this:
ID | Name and Lastname
----------------------
1 | John Something
2 | Peter Something2
3 | Mary Smith
This structure is part of my ListBox. I've builded this listbox with this code:
private void fill_people_listBox()
{
this.listBoxPeople.DataSource = db.query("SELECT ....");
this.listBoxPeople.DisplayMember = "people_name_last";
this.listBoxPeople.ValueMember = "people_id";
}
The ListBox is successfully populated. When the user wants to save the changes I've to loop throught this list to get all the selected items, but I do not need the Item, I need the ID.
Ex.:
1 | John Something.
Ignore John Something, get 1, so I do not need the DisplayMember, only the ValueMember.
To do this I've try several ways with the following:
1º
foreach (ListBox selectedItem in this.listBoxGarantes.SelectedItems)
{
selectedItem.ToString(); // just an example, I'm printing this.
}
2º
string strItem;
// insert garantes
foreach (object selectedItem in this.listBoxGarantes.SelectedItems)
{
strItem = selectedItem as String;
strItem; // just an example, I'm printing this.
}
3º And this last one among others.
foreach (ListViewItem element in this.listBoxGarantes.Items)
{
if (element.Selected)
{
element.SubItems[0].Text; // just an example, I'm printing this.
}
}
I've try several options, but I wasn't able to get succesfully the ID for each element. I do not know what else to do.
I hope anyone can help me.
Regards.
To retrieve a collection containing all selected items in a multiple-selection ListBox, use the SelectedItems property. If you want to obtain the index position of the currently selected item in the ListBox, use the SelectedIndex property.
To determine the items that are selected, you can use the Selected property of the list box. The Selected property of a list box is an array of values where each value is either True (if the item is selected) or False (if the item is not selected).
To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected. The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list: listBox1.
The ListBox control enables you to display a list of items to the user that the user can select by clicking. A ListBox control can provide single or multiple selections using the SelectionMode property.
Since you have multiple selections, the SelectedValue property won't help you much since you are enumerating through the SelectedItems list.
Try casting your items back into a DataRowView object:
foreach (var item in listBox1.SelectedItems) {
MessageBox.Show("ID = " + ((DataRowView)item)["people_id"].ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With