ComboBox SelectedValue属性不起作用

时间:2010-06-29 13:10:52

标签: c# .net winforms data-binding combobox

我正在尝试将对象添加到组合框中,并使用SelectedValue属性在组合框中选择和项目,但它不起作用:SelectedValue在赋值后仍为空。

        class ComboBoxItem
        {
            string name;
            object value;

            public string Name { get { return name; } }
            public object Value { get { return value; } }

            public ComboBoxItem(string name, object value)
            {
                this.name = name;
                this.value = value;
            }

            public override bool Equals(object obj)
            {
                ComboBoxItem item = obj as ComboBoxItem;
                return item!=null && Value.Equals(item.Value);
            }
        }          

            operatorComboBox.Items.Add(new ComboBoxItem("Gleich", SearchOperator.OpEquals));
            operatorComboBox.Items.Add(new ComboBoxItem("Ungleich", SearchOperator.OpNotEquals));


            operatorComboBox.ValueMember="Value";
            //SelectedValue is still null after this statement
            operatorComboBox.SelectedValue = SearchOperator.OpNotEquals; 

1 个答案:

答案 0 :(得分:5)

ValueMember仅适用于通过DataSource属性进行数据绑定,而不适用于使用Items.Add手动添加项目时。试试这个:

var items = new List<ComboBoxItem>();
items.Add(new ComboBoxItem(...));

operatorComboBox.DataSource = items;

顺便说一句,请注意,当您覆盖Equals时,您还应该覆盖并实施GetHashCode