根据键值对设置组合框的选择项.

nch*_*che 0 c# combobox winforms

我有一个组合框,我这样填充:

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"));
Run Code Online (Sandbox Code Playgroud)

我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个值,例如"Value1".如何将组合框的selectedItem设置为对象{Label 1,Value1}?

我试过了:

this.reqTypeInput.SelectedIndex = this.reqTypeInput.Items.IndexOf("Value1");
Run Code Online (Sandbox Code Playgroud)

bfl*_*ow1 5

看起来你正试图找到索引,好像你ComboBox只包含字符串值,当它实际包含RequestType对象时.你试过覆盖你的Equals运营商吗?

查看这篇SO帖子,以及这个覆盖的例子Equals.

编辑:正如另一个答案所提到的,一个好的做法是填充你想要的对象集合ComboBox,然后将该集合绑定到你的ComboBox.我的答案中的第一个链接就是一个例子.