BindingSource到ComboBox和[Browsable(false)]属性到PropertyGrid不能一起工作

时间:2013-07-23 17:11:34

标签: c# .net winforms combobox propertygrid

我会尝试解释我的问题。

我上课了:

public class Person()
{
        [Browsable(false)]
        public Int32 Id { get; set; }

        public string Name { get; set; }

        //...
}

我使用PropertyGrid控件来显示Name字段,但我不需要显示Id,因此我将Browsable属性设置为false,如下所示:

[Browsable(false)]
public Int32 Id { get; set; }

在我的GUI中,我在Person控件中显示ListView类的所有元素,当选择元素时,我在PropertyGrid控件中显示属性,如下所示:

void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   this.propertyGrid.SelectedObject = (object)this.listView.SelectedObject;
}

一切正常,PropertyGrid仅显示字段Name

然后我需要像这样使用ComboBox控件:

List<Person> people = new List<Person>();
people.Add(...)
//.....

this.comboBox.DataSource = new BindingSource(people, null);
this.comboBox.ValueMember = "Id"; // here an exeption has been thrown !!!
this.comboBox.DisplayMember = "Name";

在线this.comboBox.ValueMember = "Id";出现了这个错误:

System.Windows.Forms.dll中出现未处理的“System.ArgumentException”类型异常

其他信息:无法绑定到新的展示成员。

如何解决此问题?

PS:如果我删除[Browsable(false)]行,一切正常,但Id控件中的PropertyGrid字段将会显示

1 个答案:

答案 0 :(得分:5)

我复制了这个问题,我通过在设置DisplayMember和ValueMember属性后设置DataSource 解决了这个问题:

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = new BindingSource(people, null);