.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)
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
