在这里,我甚至看不到这个问题的单一正确答案(在WinForms标签中),并且这种常见问题很奇怪.
一个项ListBox控制可以是DataRowView,复杂对象,匿名类型,原发性类型和其他类型.项目的基础价值应根据基础计算ValueMember.
ListBoxcontrol有一个GetItemText帮助您获取项目文本的控件,无论您添加为项目的对象类型如何.它真的需要这样的GetItemValue方法.
GetItemValue扩展方法
我们可以创建GetItemValue 扩展方法来获取项目值,其工作方式如下GetItemText:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用上述方法,您无需担心设置,ListBox并且它将返回Value项目的预期.它适用于List<T>,Array,ArrayList,DataTable,匿名类型,主要类型的列表,你可以作为数据源使用所有其他列表的列表.以下是一个用法示例:
//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Run Code Online (Sandbox Code Playgroud)
由于我们将GetItemValue方法创建为扩展方法,因此当您想要使用该方法时,请不要忘记包含您将该类放入的命名空间.
这种方法适用于ComboBox与CheckedListBox过.
如果您正在处理Windows窗体项目,可以尝试以下操作:
将项添加到ListBoxas KeyValuePair对象:
listBox.Items.Add(new KeyValuePair(key, value);
Run Code Online (Sandbox Code Playgroud)
然后,您将能够通过以下方式检索它们:
KeyValuePair keyValuePair = listBox.Items[index];
var value = keyValuePair.Value;
Run Code Online (Sandbox Code Playgroud)
这对我有用:
ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));
Console.Write(x.Items[0].Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
126459 次 |
| 最近记录: |