Set the selecteditem of a combobox based on key,value pair.

后端 未结 4 856
情深已故
情深已故 2021-01-27 17:32

I have a combobox that I populate like this:

this.reqTypeInput.Items.Add(new RequestType(\"Label 1\", \"Value1\"));
this.reqTypeInput.Items.Add(new RequestType(\         


        
相关标签:
4条回答
  • 2021-01-27 18:02

    It looks like you are trying to find the index as though your ComboBox contains just string values, when it actually contains RequestType objects. Have you tried overriding your Equals operator?

    Check out this SO post, and this one for examples of overriding Equals.

    EDIT: As mentioned in another answer, a good practice is to populate a collection of objects that you want in the ComboBox, then bind that collection to your ComboBox. The first link in my answer here has an example of that.

    0 讨论(0)
  • 2021-01-27 18:05

    You can try this:

    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.

    0 讨论(0)
  • 2021-01-27 18:12

    Lot's of choices, List, SortedList, Dictionary, SortedDictionary. But basicall you keep your collection of RequestTypes in a list and then populate the combo from it, you could even bind if you wish.

    The only thing the combo knopws about your collection of request types, is the result of each RequestType's ToString method. If you want find by Value, then Combox will only see waht you put in it, which was RequestType.ToString()

    0 讨论(0)
  • 2021-01-27 18:15

    If the request types do not change, you could store each RequestType object in a variable first, then set the SelectedItem property of the ComboBox to that variable.

    For example:

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

    Then, set it like this:

    reqTypeInput.SelectedItem = type2;
    
    0 讨论(0)
提交回复
热议问题