为什么 DisplayMember 不适用于 ListBox 中手动添加的 DataRow?
Why DisplayMember doesn't work with manually added DataRow in ListBox?
我在 this.listBox1.Items
中手动添加了一些 DataRow,并在 WinForms Designer 中将 DisplayMember
设置为列名,但稍后显示的只是类型名称列表(System.Data...) 。
如何解决这个问题?
代码:
list1.ForEach(x => this.listBox1.Items.Add(x)); //x is DataRow from a filled DataTable
指定要添加到列表框中的列名称:
list1.ForEach(x => this.listBox1.Items.Add(x["column_name"]));
DisplayMember
和 ValueMember
仅在使用数据绑定 (ListBox.DataSource
) 时适用。它们要么使用可通过反射检索的真实属性,要么通过 .NET 组件模型和 ICustomTypeDescriptor
接口工作。
如果直接绑定 DataTable
,GetEnumerator
方法和 IList
实现 returns 总是 DataRowView
个实例而不是 DataRow
秒。 DataRowView
实现 ICustomTypeDescriptor
,其中 DisplayName
可以引用列名。
因此,如果您想添加一些自定义筛选列表,我建议您从任何来源创建一个。例如:
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Value";
var list = Enumerable.Range(1, 10).Select(i => new {Name = i.ToString(), Value = i}).ToList();
listBox1.DataSource = list;
如果Name
属性存在,你会看到它的值;否则,您将看到 ToString
个项目。
但是,如果您以编程方式添加项目 (ListBox.Items
),这些属性将被忽略,并且将始终使用项目的 ToString
。
我在 this.listBox1.Items
中手动添加了一些 DataRow,并在 WinForms Designer 中将 DisplayMember
设置为列名,但稍后显示的只是类型名称列表(System.Data...) 。
如何解决这个问题?
代码:
list1.ForEach(x => this.listBox1.Items.Add(x)); //x is DataRow from a filled DataTable
指定要添加到列表框中的列名称:
list1.ForEach(x => this.listBox1.Items.Add(x["column_name"]));
DisplayMember
和 ValueMember
仅在使用数据绑定 (ListBox.DataSource
) 时适用。它们要么使用可通过反射检索的真实属性,要么通过 .NET 组件模型和 ICustomTypeDescriptor
接口工作。
如果直接绑定 DataTable
,GetEnumerator
方法和 IList
实现 returns 总是 DataRowView
个实例而不是 DataRow
秒。 DataRowView
实现 ICustomTypeDescriptor
,其中 DisplayName
可以引用列名。
因此,如果您想添加一些自定义筛选列表,我建议您从任何来源创建一个。例如:
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Value";
var list = Enumerable.Range(1, 10).Select(i => new {Name = i.ToString(), Value = i}).ToList();
listBox1.DataSource = list;
如果Name
属性存在,你会看到它的值;否则,您将看到 ToString
个项目。
但是,如果您以编程方式添加项目 (ListBox.Items
),这些属性将被忽略,并且将始终使用项目的 ToString
。