Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用C从列表框中的选定项获取ValueMember#_C#_Listbox_Selecteditem_Valuemember - Fatal编程技术网

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

C# 使用C从列表框中的选定项获取ValueMember#,c#,listbox,selecteditem,valuemember,C#,Listbox,Selecteditem,Valuemember,我正在尝试从带有C#的列表框中获取所有选定项的ValueMember 例如: 我有一张这样的清单: ID | Name and Lastname ---------------------- 1 | John Something 2 | Peter Something2 3 | Mary Smith 此结构是我的列表框的一部分。我用以下代码构建了这个列表框: private void fill_people_listBox() { this.listBoxPeople.DataS

我正在尝试从带有C#的列表框中获取所有选定项的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"; 
}
列表框已成功填充。当用户想要保存更改时,我必须循环此列表以获取所有选定的项,但我不需要该项,我需要ID

例:

忽略John某事,获取1,因此我不需要DisplayMember,只需要ValueMember

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

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

尝试一下
this.listBoxPeople.SelectedValue
,但我选择了几个值。我应该把这个.listBoxPeople.SelectedValue放在哪里?然后使用您的第一个代码段并用just var替换ListBox,然后您将不得不将对象强制转换为它是什么,这还不清楚db.query返回的是什么。数据表中的数据行?是的,这是一个数据表。非常感谢!!你帮了我很多!:)
        string strItem;

        // insert garantes
        foreach (object selectedItem in this.listBoxGarantes.SelectedItems)
        {
            strItem = selectedItem as String;

            strItem; // just an example, I'm printing this.
        }
        foreach (ListViewItem element in this.listBoxGarantes.Items)
        {
            if (element.Selected)
            {
                element.SubItems[0].Text; // just an example, I'm printing this.
            }
        }
foreach (var item in listBox1.SelectedItems) {
  MessageBox.Show("ID = " + ((DataRowView)item)["people_id"].ToString());
}