.NET 3.5 Listbox Selected Values (Winforms)(.NET 3.5 列表框选定值(Winforms))
问题描述
我正在努力从启用了多选并已绑定到获取名称(作为 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.NET 3.5 列表框选定值(Winforms)


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01