使用c#从列表框中的选定项中获取ValueMember

本文关键字:获取 ValueMember 列表 使用 | 更新日期: 2023-09-27 17:50:46

我正在尝试从c#列表框中获取所有选定的项目ValueMember。

为例:

我有一个这样的清单:

ID | Name and Lastname
----------------------
1  | John Something
2  | Peter Something2
3  | Mary Smith

这个结构是我的ListBox的一部分。我用下面的代码构建了这个列表框:

private void fill_people_listBox()
{
    this.listBoxPeople.DataSource = db.query("SELECT ....");
    this.listBoxPeople.DisplayMember = "people_name_last";
    this.listBoxPeople.ValueMember = "people_id"; 
}

ListBox已成功填充。当用户想保存更改时,我必须遍历该列表以获取所有选中的项目,但是我不需要Item,我需要的是ID。

例:

1 | John Something.

忽略John Something,得到1,所以我不需要DisplayMember,只需要ValueMember。

为了做到这一点,我尝试了以下几种方法: 1º

        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º还有最后一个。

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

我已经尝试了几个选项,但我不能成功地获得每个元素的ID。我不知道还能做什么。

我希望任何人都能帮助我。

问候。

使用c#从列表框中的选定项中获取ValueMember

由于您有多个选择,因此SelectedValue属性对您没有多大帮助,因为您正在枚举SelectedItems列表。

试着将你的项目转换回DataRowView对象:

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