组合框SelectedValue属性不起作用 [英] ComboBox SelectedValue property doesn't work
本文介绍了组合框SelectedValue属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想添加对象到组合框,并使用的SelectedValue
属性在组合框中选择和项目,但它不工作:的SelectedValue
仍是空的分配之后。
类ComboBoxItem
{
字符串名称;
对象的值;
公共字符串名称{{返回名称; }}
公共对象值{{返回值; }}
公共ComboBoxItem(字符串名称,对象的值)
{
this.name =名称;
THIS.VALUE =价值;
}
公众覆盖布尔等于(obj对象)
{
ComboBoxItem项目= OBJ为ComboBoxItem;
返回项目= NULL和放大器;!&安培; Value.Equals(item.Value);
}
}
operatorComboBox.Items.Add(新ComboBoxItem(GLEICH,SearchOperator.OpEquals));
operatorComboBox.Items.Add(新ComboBoxItem(Ungleich,SearchOperator.OpNotEquals));
operatorComboBox.ValueMember =值;
//的SelectedValue仍然是该语句之后空
operatorComboBox.SelectedValue = SearchOperator.OpNotEquals;
解决方案
ValueMember
通过数据源绑定时只适用
属性,而不是当你与 Items.Add
。试试这个:
VAR项目=新的名单,其中,ComboBoxItem>();
items.Add(新ComboBoxItem(...));
operatorComboBox.DataSource =项目;
顺便说一句,请注意,当您覆盖等于
,你也应该覆盖和实施 GetHash code
。
I'm trying to add objects into a combobox and use SelectedValue
property to select and item in the combobox but it does not work: SelectedValue
is still null after the assignment.
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;
解决方案
ValueMember
is only applicable when databinding via DataSource
property, not when you add items manually with Items.Add
. Try this:
var items = new List<ComboBoxItem>();
items.Add(new ComboBoxItem(...));
operatorComboBox.DataSource = items;
Btw, note that when you override Equals
, you should also override and implement GetHashCode
.
这篇关于组合框SelectedValue属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文