C# 根据键、值对设置组合框的selecteditem。
我有一个组合框,我这样填充:C# 根据键、值对设置组合框的selecteditem。,c#,winforms,combobox,C#,Winforms,Combobox,我有一个组合框,我这样填充: this.reqTypeInput.Items.Add(new RequestType("Label 1", "Value1")); this.reqTypeInput.Items.Add(new RequestType("Label 2", "value2")); this.reqTypeInput.Items.Add(new RequestType("Label 3", "value3")); reqTypeInput.SelectedItem = type2
this.reqTypeInput.Items.Add(new RequestType("Label 1", "Value1"));
this.reqTypeInput.Items.Add(new RequestType("Label 2", "value2"));
this.reqTypeInput.Items.Add(new RequestType("Label 3", "value3"));
reqTypeInput.SelectedItem = type2;
我的RequestType类是:
class RequestType
{
public string Text { get; set; }
public string Value { get; set; }
public RequestType(string text, string val)
{
Text = text;
Value = val;
}
public override string ToString()
{
return Text;
}
}
我有一个值,例如“Value1”。如何将组合框的selectedItem设置为对象{Label 1,Value1}
我试过:
this.reqTypeInput.SelectedIndex = this.reqTypeInput.Items.IndexOf("Value1");
如果请求类型没有改变,您可以先将每个RequestType对象存储在一个变量中,然后将ComboBox的属性设置为该变量 例如:
RequestType type1 = New RequestType("Label 1", "Value 1");
RequestType type2 = New RequestType("Label 2", "Value 2");
reqTypeInput.Items.Add(type1);
reqTypeInput.Items.Add(type2);
然后,设置如下:
this.reqTypeInput.Items.Add(new RequestType("Label 1", "Value1"));
this.reqTypeInput.Items.Add(new RequestType("Label 2", "value2"));
this.reqTypeInput.Items.Add(new RequestType("Label 3", "value3"));
reqTypeInput.SelectedItem = type2;
看起来您正试图查找索引,好像您的
组合框
只包含字符串值,而实际上它包含RequestType
对象。您是否尝试重写Equals
运算符
签出,并获取覆盖等于的示例
编辑:如另一个答案所述,一个好的做法是在组合框
中填充所需对象的集合,然后将该集合绑定到您的组合框
。我的答案中的第一个链接有一个例子。你可以试试这个:
RequestType type1 = New RequestType("Label 1", "Value 1");
RequestType type2 = New RequestType("Label 2", "Value 2");
reqTypeInput.Items.Add(type1);
reqTypeInput.Items.Add(type2);
this.reqTypeInput.SelectedIndex = this.reqTypeInput.Items.IndexOf(type1);
HTH.有很多选择,列表,分类列表,词典,分类词典。
但是如果您将RequestTypes集合保存在一个列表中,然后从中填充组合,您甚至可以根据需要绑定
组合体对请求类型集合唯一了解的是每个请求类型的ToString方法的结果。如果您希望按值查找,那么Combox将只看到您在其中放入的内容,即RequestType.ToString()