如何获得列表框所选项目的值 [英] 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
但是,当我尝试此操作时,'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.
这篇关于如何获得列表框所选项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!