我正在尝试使用 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。
为此,我尝试了以下几种方法:
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。我不知道还能做什么。
我希望有人能帮助我。
问候。
最佳答案
由于您有多个选择,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/