Search code examples
c#winformscombobox

Right way to set selected text of combobox in winforms?


I have a form that takes in an object in it's constructor and populates controls on the form from properties in that object. I am having an issue where I can't set a ComboBox's SelectedText property, or at least it isn't working how I expect it to.

public Form(ValueHoldingObject obj)
{
    // yeah I know this is not a very clean way to populate the combobox, the issue
    // isn't limited to the combobox so I don't think this is relevant
    List<int> items = Repo.GetAllItems().Reverse();
    foreach (int id in checkInPrizeIds.Take(100))
        // Insert at beginning to put more recently used items at the top
        combobox.Items.Insert(0, id);
    combobox.DropDownHeight = 200;

    combobox.SelectedText = obj.StringProperty;
}

When I am testing this form the text of the combobox isn't being populated. If I add a breakpoint on the line where I assign the text it DOES get assigned, so some event is firing (multiple focus change events probably) and making it work the way I want. Obviously I can't use a breakpoint as a fix in production code. Am I assigning this value incorrectly? Should I be using a different method to populate the values?

Further testing has reviled that it isn't just the combobox, all of my controls are only being populated correctly if I have the breakpoint.


Solution

  • In the constructor, you need to set the selected item, for example:

    foreach ( var item in combobox.Items )
    if ( (string)item == obj.StringProperty )
      combobox.SelectedItem = item;
    

    Or:

    foreach ( var item in combobox.Items )
      if ( (int)item == Convert.ToInt32(obj.StringProperty) )
          combobox.SelectedItem = item;
    

    It's confusing but despite its name, the property SelectedText is not really the selected item... because combo box items are objects and not strings: texts shown are a representation of the item objects using ToString().

    Therefore setting the selected text will not guarantee to select an item and we can prefer setting the SelectedItem.

    In addition to these considerations, you set the selected text property in the constructor after populating the combo box and that can cause problems because it is before the form and the control are drawn or something like that... that is to say perhaps before the ToString() methods are called on items to prepare the visual cache, so setting the selected text can't get a match with the list.

    Setting the selected text selects an existing item if done in the form load or shown events.

    private void Form_Load(object sender, EventArgs e)
    {
      combobox.SelectedText = obj.StringProperty;
    }
    

    ComboBox.SelectedText doesn't give me the SelectedText

    ComboBox.SelectedText Property