using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
7 回答
这将是
在这里,我甚至看不到这个问题的单一正确答案(在WinForms标签中),并且这种常见问题很奇怪 .
ListBox
控件的项目可以是DataRowView
,复杂对象,匿名类型,主要类型和其他类型 . 项目的基础 Value 应根据ValueMember
计算 .ListBox
control具有GetItemText
,无论您添加为项目的对象类型如何,它都可以帮助您获取项目文本 . 它真的需要这样的方法 .GetItemValue Extension Method
我们可以创建
GetItemValue
extension method来获取类似于GetItemText的项目值:使用上述方法,您无需担心
ListBox
的设置,它将返回项目的预期Value
. 它适用于List<T>
,_Array
,ArrayList
,_DataTable
,匿名类型列表,主要类型列表以及可用作数据源的所有其他列表 . 以下是一个用法示例:由于我们创建了
GetItemValue
方法作为扩展方法,因此当您想要使用该方法时,请不要忘记包含您将该类放入的命名空间 .此方法也适用于
ComboBox
和CheckedListBox
.如果您正在处理Windows窗体项目,可以尝试以下操作:
将项目添加到
ListBox
作为KeyValuePair
对象:然后,您将能够通过以下方式检索它们:
我正在使用一个带有SqlDataReader的BindingSource,并且以上都不适用于我 .
微软的问题:为什么这样做:
但这不是吗?
我发现我必须回到BindingSource对象,将其转换为System.Data.Common.DbDataRecord,然后引用它的列名:
现在那太荒谬了 .
假设您想要第一个项目的值 .
这对我有用:
只需尝试这个listBox就是你的列表,yu是一个可靠的索引0的值将被分配