问题描述
我正在使用 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.
这篇关于如何获取列表框选定项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!