在这里,我甚至看不到这个问题的单一正确答案(在WinForms标签中),并且这种常见问题很奇怪 .
ListBox 控件的项目可以是 DataRowView ,复杂对象,匿名类型,主要类型和其他类型 . 项目的基础 Value 应根据 ValueMember 计算 .
ListBox control具有 GetItemText ,无论您添加为项目的对象类型如何,它都可以帮助您获取项目文本 . 它真的需要这样的方法 .
GetItemValue Extension Method
我们可以创建 GetItemValue extension method来获取类似于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