【发布时间】:2014-04-24 14:29:30
【问题描述】:
我正在尝试使用 C# 从 ListBox 中获取所有选定项 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 已成功填充。当用户想要保存更改时,我必须遍历此列表以获取所有选定的项目,但我不需要项目,我需要 ID。
例如:
1 | John Something.
Ignore John Something,得到 1,所以我不需要 DisplayMember,只需要 ValueMember。
为此,我尝试了以下几种方法:
1º
foreach (ListBox selectedItem in this.listBoxGarantes.SelectedItems)
{
selectedItem.ToString(); // just an example, I'm printing this.
}
2º
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。我不知道还能做什么。
希望有人能帮助我。
问候。
【问题讨论】:
-
试试
this.listBoxPeople.SelectedValue -
但我有几个选定的值。我应该把 this.listBoxPeople.SelectedValue 放在哪里?
-
然后使用你的第一个 sn-p 并用 var 替换 ListBox,然后你将不得不将对象转换为它是什么,这不清楚 db.query 返回什么。数据表中的数据行?
-
是的,它是一个数据表。
标签: c# listbox selecteditem valuemember