.NET 3.5 列表框选定值 (Winforms)
我正在努力从启用了多选并已绑定到数据库表的 Winforms 列表框中获取选定的值(请注意值而不是文本),获取名称(作为 DisplayMember)和 ID(作为 ValueMember) - 我需要所选项目的 ID。
列表框控件具有 SelectedValue
属性,用于获取选定项值之一,但不能获取所有选定项值。
SelectedItems
属性返回一个 Listbox.SelectedObjectCollection
我似乎无法从中提取项目的值。
请帮忙!谢谢。
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.
The listbox control has properties for SelectedValue
to get one of the selected items values, but not for all selected items values.
The SelectedItems
property returns a Listbox.SelectedObjectCollection
from which I cannot seem to extract the VALUES of the items.
Please help! Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将集合中的每个
对象
转换为所需的类型
。例如,如果我的项目属于Customer
类型,我可以执行以下操作...现在您可以从
Customer
获取所需的任何属性。这只是一个简单的例子,但我相信您可以将这个概念应用于您的问题。
更新(问题更新后表明列表框已绑定到表):
如果您绑定到
DataTable
,您可以尝试这样的操作(同样,微不足道,但相关):Try casting each
object
in the collection to the desiredtype
. For example, if my items are of typeCustomer
, I could do something like this...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.
UPDATE (after question was updated to indicate the Listbox is bound to table):
If you're bound to a
DataTable
, you could try something like this (again, trivial but relevent):SelectedItems 就是您想要的。
仅当您设置 DisplayMember 和 ValueMember 时,SelectedItem 和 SelectedValue 才会不同。我认为多选不支持此功能。
您要添加到列表框中的项目是什么类型?
SelectedItems is what you want.
SelectedItem and SelectedValue are only different when you set DisplayMember and ValueMember. I don't think this is supported for Multi-select.
What type of Items are you adding to the listbox?
元素[0] 将是“ValueMember”,元素[1] 将是“DisplayMember”。假设 OP 的“ID”字段是一个整数,请尝试以下操作:
Element [0] will be the "ValueMember", and element [1] will be the "DisplayMember". Assuming the OP's "ID" field is an integer, try the following: