How to get listbox selected item value(如何获取列表框选定项的值)
问题描述
我正在使用 C# .NET 4.0
I am working with C# .NET 4.0
我正在尝试获取列表框中单个选定项目的值.
I am trying to get the value of a single selected item in a listbox.
这就是我填充控件的方式:
This is how I populate the control:
this.files_lb.DataSource = DataTable object
在我的设计器中,我将 file_name 指定为 DisplayMember,将 file_id 指定为 DisplayValue
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
在列表框中选择一个项目后,我尝试了以下获取值:
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
但它返回的只是 "System.Data.DataRowView".
在此链接:获取所选项目的价值在列表框中作为字符串
有人建议-
String SelectedItem = listBox1.SelectedItem.Value
但是,当我尝试这个时,价值"不是一个选项.
However, 'Value' is not an option when I try this.
如何从列表框中的单个选定项目中获取 ValueMember 值?
How can I get the ValueMember value from a single selected item in a listbox?
推荐答案
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
将 columnName 替换为您要从中获取数据的列的名称,这将与您的数据源中的列相对应.
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
如果没有选定的项目,还要注意空值.
Also watch out for nulls if there's no selected item.
这篇关于如何获取列表框选定项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取列表框选定项的值
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
