Getting ValueMember from selected item in ListBox with C #

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:

        foreach (ListBox selectedItem in this.listBoxGarantes.SelectedItems)
        {
            selectedItem.ToString(); // just an example, I'm printing this.

        }

        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 is the last among others.

        foreach (ListViewItem element in this.listBoxGarantes.Items)
        {
            if (element.Selected)
            {
                element.SubItems[0].Text; // just an example, I'm printing this.
            }
        }

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.

.

+4
1

, SelectedValue , SelectedItems.

DataRowView:

foreach (var item in listBox1.SelectedItems) {
  MessageBox.Show("ID = " + ((DataRowView)item)["people_id"].ToString());
}
+3

Source: https://habr.com/ru/post/1532343/


All Articles