Getting ValueMember from selected item in a ListBo

2019-05-02 00:30发布

问题:

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:

        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 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.

回答1:

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());
}