问题描述
我正在努力从启用了多选并已绑定到获取名称(作为 DisplayMember)和 ID(作为 ValueMember)的数据库表的 Winforms 列表框中获取选定的值(请注意 VALUES 不是 TEXT)-我需要所选项目的 ID.
I am BATTLING to get the selected values (please note VALUES not TEXT) from a Winforms Listbox that has multi-select enabled and has been bound to a database table getting the Name (as DisplayMember) and ID (as ValueMember) - I need the ID of the selected items.
列表框控件具有 SelectedValue
的属性,用于获取选定项值之一,但不是所有选定项值.
The listbox control has properties for SelectedValue
to get one of the selected items values, but not for all selected items values.
SelectedItems
属性返回一个 Listbox.SelectedObjectCollection
,我似乎无法从中提取项目的值.
The SelectedItems
property returns a Listbox.SelectedObjectCollection
from which I cannot seem to extract the VALUES of the items.
请帮忙!谢谢.
推荐答案
尝试将集合中的每个 object
转换为所需的 type
.例如,如果我的商品是 Customer
类型,我可以这样做...
Try casting each object
in the collection to the desired type
. For example, if my items are of type Customer
, I could do something like this...
var selected = listBox1.SelectedItems;
foreach ( var item in selected )
{
var singleCustomer = (Customer)item;
}
现在你可以从客户
那里得到你想要的任何属性.
Now you can get any property you want from the Customer
.
这只是一个简单的例子,但我相信你可以将这个概念应用到你的问题中.
This is just a trivial example, but I'm sure you can apply the concept to your problem.
更新(在更新问题以指示列表框绑定到表之后):
如果您绑定到 DataTable
,您可以尝试这样的事情(同样,微不足道但相关):
If you're bound to a DataTable
, you could try something like this (again, trivial but relevent):
var selected = listBox1.SelectedItems;
foreach ( var item in selected )
{
var itemArray = ( (DataRowView)item ).Row.ItemArray;
var name = itemArray[0];
var id = itemArray[1];
}
这篇关于.NET 3.5 列表框选定值(Winforms)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!