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

标签 c# listbox selecteditem valuemember

我正在尝试使用 C# 从 ListBox 中获取所有选定的项目 ValueMember。

例如:

我有一个这样的列表:

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

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

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

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

例如:

1 | John Something.

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

为此,我尝试了以下几种方法:

        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。我不知道还能做什么。

我希望有人能帮助我。

问候。

最佳答案

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

尝试将您的项目转换回 DataRowView 对象:

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

关于c# - 使用 C# 从列表框中的选定项获取 ValueMember,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22487326/

相关文章:

c# - WindowsBase.dll 中发生类型为 'System.InvalidCastException' 的第一次机会异常

c# - 相同的 ItemSource,但每个列表框都有另一个 View

c# - 如何将程序集加载到具有不同目标框架的单独应用程序域中?

c# - Directory.GetFiles - 文件扩展名的搜索模式

wpf - 在 WPF 列表框中选择项目时显示刻度图像

C# MVVM : Edit a SelectedItem of an ObservableCollection with a RelayCommand

mvvm - AutoCompleteBox 不要在向下/向上键上选择项目

angular - 无法在angular7 ng-select中使用ngModel设置所选项目值

c# - 如何更改任务中的值

c# - 在 wcf 的 datacontract 类中公开方法