65.9K
CodeProject 正在变化。 阅读更多。
Home

向绑定的组合框添加项

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.62/5 (16投票s)

2006年10月7日

CPOL

1分钟阅读

viewsIcon

171749

downloadIcon

1793

本文展示了如何向数据绑定的组合框添加新项。

问题场景

Windows Forms ComboBox 控件用于在下拉组合框中显示数据。当组合框的数据源属性与数据绑定时,您将无法通过 Items.Add() 函数添加任何项目。

因此,让我们通过一个演示来了解问题场景及其解决方案。假设我们有一个名为 Person 的类,我们将创建一个 IList 来存储此 Person 列表。

Person p = null;
IList list = new ArrayList();

p = new Person();
p.PersonID = 1;
p.PersonName = "Ali";
list.Add(p);

p = new Person();
p.PersonID = 2;
p.PersonName = "Raza";
list.Add(p);

p = new Person();
p.PersonID = 3;
p.PersonName = "Shaikh";
list.Add(p);

我们已经在列表中添加了三个人的信息,现在我们想将组合框与此数据绑定。

this.comboBox1.DataSource = list;
this.comboBox1.DisplayMember = "PersonName";
this.comboBox1.ValueMember = "PersonID";

现在,数据已绑定到组合框,我们将在界面上看到类似以下的内容。

现在,这里有什么问题?在大多数专业应用程序中,每个组合框的顶部都有一个选择选项,以便用户可以选择一个选项(如果需要),或者不选择任何内容就离开组合框。因此,作为一种常见做法,人们会编写以下代码

this.comboBox1.Items.Add("< Select Person >");
//OR
this.comboBox1.Items.Insert(0, "< Select Person >");

最终会得到这个错误

解决方案

可以使用 System.Reflection 的以下两个类来实现这一点

  • Activator:包含用于本地或远程创建对象类型,或获取现有远程对象引用的方法
  • PropertyInfo:发现属性的属性并提供对属性元数据的访问。

现在,只需调用此函数即可在列表中添加所需的项目。

private void AddItem(IList list, Type type, string valueMember, 
	string displayMember, string displayText)
{
            //Creates an instance of the specified type 
            //using the constructor that best matches the specified parameters.
            Object obj = Activator.CreateInstance(type);

            // Gets the Display Property Information
            PropertyInfo displayProperty = type.GetProperty(displayMember);

            // Sets the required text into the display property
            displayProperty.SetValue(obj, displayText, null);

            // Gets the Value Property Information
            PropertyInfo valueProperty = type.GetProperty(valueMember);

            // Sets the required value into the value property
            valueProperty.SetValue(obj, -1, null);

            // Insert the new object on the list
            list.Insert(0, obj);
}

然后在数据与组合框绑定之前添加以下代码行

AddItem(list, typeof(Person), "PersonID", "PersonName", "< Select Option >");

最终,界面看起来像这样,看起来像是在处理组合框中的数据方面做出了专业的努力。

历史

  • 2006年10月7日:初始发布
© . All rights reserved.