获取ValueMember从所选项目在ListBox用C# [英] Getting ValueMember from selected item in a ListBox with C#

查看:158
本文介绍了获取ValueMember从所选项目在ListBox用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用C#一个ListBox所有选定项目ValueMember

I'm trying to get all the selected items ValueMember from a ListBox with C#.

有关例如:

我有这样一个列表:

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

这结构我ListBox中的一部分。我已经建造这个列表框使用此代码:

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"; 
}



列表框成功填充。当用户想保存我有循环throught这个名单来获取所有所选项目的变化,但我并不需要的项目,我需要的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.

例如:

1 | John Something.



忽略约翰东西,拿到1,所以我不需要的DisplayMember,只有ValueMember。

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°和他人之间这最后一个。

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.

我希望有人能帮助我。

问候。

推荐答案

既然你有多个选择,因为你是通过SelectedItems名单列举SelectedValue属性不会帮你了。

Since you have multiple selections, the SelectedValue property won't help you much since you are enumerating through the SelectedItems list.

尝试投您的项目回一个DataRowView的对象:

Try casting your items back into a DataRowView object:

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

这篇关于获取ValueMember从所选项目在ListBox用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆