2010-06-29 144 views
1

我试图将对象添加到组合框中,并使用SelectedValue属性在组合框中选择和项目,但它不起作用:SelectedValue在赋值后仍为空。ComboBox 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; 

回答

5

ValueMember通过DataSource属性绑定时,不是当你与Items.Add手动添加物品才适用。试试这个:

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

operatorComboBox.DataSource = items; 

顺便说一句,请注意,当你重写Equals,你也应该重写和实现GetHashCode