【问题标题】:Set the selecteditem of a combobox based on key,value pair.根据键值对设置组合框的选定项。
【发布时间】:2011-12-02 14:02:00
【问题描述】:

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

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"));

我的 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");

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    看起来您正在尝试查找索引,就好像您的 ComboBox 只包含字符串值,而实际上它包含 RequestType 对象。您是否尝试过覆盖 Equals 运算符?

    查看this SO postthis one 以获取覆盖Equals 的示例。

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

    【讨论】:

      【解决方案2】:

      如果请求类型没有改变,您可以先将每个 RequestType 对象存储在一个变量中,然后将 ComboBox 的 SelectedItem 属性设置为该变量。

      例如:

      RequestType type1 = New RequestType("Label 1", "Value 1");
      RequestType type2 = New RequestType("Label 2", "Value 2");
      
      reqTypeInput.Items.Add(type1);
      reqTypeInput.Items.Add(type2);
      

      然后,这样设置:

      reqTypeInput.SelectedItem = type2;
      

      【讨论】:

        【解决方案3】:

        你可以试试这个:

        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。

        【讨论】:

          【解决方案4】:

          有很多选择,List、SortedList、Dictionary、SortedDictionary。 但基本上你将你的 RequestTypes 集合保存在一个列表中,然后从中填充组合,如果你愿意,你甚至可以绑定。

          combo 唯一了解您的请求类型集合的是每个 RequestType 的 ToString 方法的结果。如果你想按值查找,那么 Combox 只会看到你放入的内容,即 RequestType.ToString()

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-05-19
            • 2016-03-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多