I am trying to get all selected ValueMember elements from a ListBox with C #.
For instance:
I have 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 created this list using this code:
private void fill_people_listBox()
{
this.listBoxPeople.DataSource = db.query("SELECT ....");
this.listBoxPeople.DisplayMember = "people_name_last";
this.listBoxPeople.ValueMember = "people_id";
}
ListBox successfully populated. When the user wants to save the changes, I have to go through this list to get all the selected elements, but I do not need the element, I need the identifier.
Example:.
1 | John Something.
Ignore John Something, get 1, so I don't need DisplayMember, only ValueMember.
For this, I will try several ways with the following:
1º
foreach (ListBox selectedItem in this.listBoxGarantes.SelectedItems)
{
selectedItem.ToString();
}
2º
string strItem;
foreach (object selectedItem in this.listBoxGarantes.SelectedItems)
{
strItem = selectedItem as String;
strItem;
}
3º And this is the last among others.
foreach (ListViewItem element in this.listBoxGarantes.Items)
{
if (element.Selected)
{
element.SubItems[0].Text;
}
}
I tried several options, but I could not get the identifier for each element. I do not know what else to do.
I hope someone can help me.
.