12

I am creating a combobox from a List of KeyValuePair<int, string>. So far it has been working very well in offering the user the descriptive name while returning me a numeric id.
However, whatever I try, I am not able to choose the initially selected value.

public StartUpForm()
{
    InitializeComponent();

    FlowLayoutPanel flowLayout = new FlowLayoutPanel(); //This is necessary to protect the table, which is for some reason collapsing...
    flowLayout.FlowDirection = FlowDirection.TopDown;
    flowLayout.AutoSize = true;
    flowLayout.AutoSizeMode = AutoSizeMode.GrowAndShrink;

    var comboBox = new ComboBox();

    {
        var choices = new List<KeyValuePair<int, string>> ();
        choices.Add(new KeyValuePair<int, string>(1, "hello"));
        choices.Add(new KeyValuePair<int, string>(2, "world"));
        comboBox.DataSource = choices;
        comboBox.ValueMember = "Key";
        comboBox.DisplayMember = "Value";
        flowLayout.Controls.Add(comboBox);
    }
    Controls.Add(flowLayout);

    //None of these work:
    comboBox.SelectedValue = 2;
    comboBox.SelectedValue = 2.ToString();
    comboBox.SelectedValue = new KeyValuePair<int, string>(2, "world");
    comboBox.SelectedValue = "world";
    comboBox.SelectedItem = 2;
    comboBox.SelectedItem = 2.ToString();
    comboBox.SelectedItem = new KeyValuePair<int, string>(2, "world");
    comboBox.SelectedItem = "world";

    return;
}

The result is always the same:

enter image description here

How can I choose the initially selected value in a ComboBox using as DataSource a List<KeyValuePair<int, string>>?

2 Answers 2

8
+50

Binding doesn't work very well inside the constructor, so try moving the ComboBox declaration to the form scope and try using the OnLoad override:

ComboBox comboBox = new ComboBox();

protected override void OnLoad(EventArgs e) {
  comboBox.SelectedValue = 2;
  base.OnLoad(e);
}
2
  • Fantastic, it works! Thanks! One question: How is one supposed to know this?
    – Antonio
    Commented Sep 23, 2015 at 22:07
  • @Antonio Had the same problem . . . years and years ago.
    – LarsTech
    Commented Sep 23, 2015 at 22:08
1

Why are you using binding? Wouldn't it be easier to create a class with the int and the string properties and override ToString() to show the string text:

public class ComboItem
{
    public int Key {get; set;}
    public string Text {get; set;}
    public override string ToString()
    {
        return this.Text;
    }
}

public void OnFormLoad(object Sender, ...)
{
    IEnumerable<ComboItem> comboItems = CreateListComboItems();
    this.ComboBox1.Items.Clear();
    foreach (var comboitem in comboItems)
    {
        this.comboBox1.Items.Add(comboItem);
    }
 }

Subscribe to comboBox event SelectedIndexChanged:

private void OnComboSelectedIndexChanged(object sender, EventArgs e)
{
    ComboItem selectedItem = (ComboItem)this.comboBox1.SelectedItem;
    ProcessSelectedKey(selectedItem.Key);
}

Addendum: I am not able to choose the initially selected value.

I guess you want to be able to programmatically select the combo box item that has a Key with a given value, causing the ComboBox to display the Text belonging to that key.

Although property ComboBox.Items is of type ComboBoxCollection, it implements IEnumerable, meaning you can use Enumerable.Cast() on it to cast it to a sequence of ComboItems. Use Linq to find if there is a ComboItem with the requested key and select the first found ComboItem, or select or select nothing if there is no ComboItem with this key

// selects the combobox item with key == value
private void SelectComboItem(int value)
{
   this.comboBox1.SelectedItem = 
       this.ComboBox1.Items.Cast<ComboItem>()
           .FirstOrDefault(comboItem => comboItem.Key == value);
}

The code will get the collection of items in the combo box (which we know is a sequence of ComboItems), hence we can cast all items to a ComboItem. Then we try to find the first ComboItem that has a Key equal to value. Return null if there is no such ComboItem. Finally make it the selected item. A value of null indicates to select nothing

5
  • 1
    Why reinventing wheel?
    – Antonio
    Commented Oct 8, 2015 at 10:10
  • You mean why reuse patterns that have been proven to work? Well (1) ease of use, (2) ease of understanding for future changes of your class, (3) ease of change, for instance if in future we need two key values instead of one Commented Oct 8, 2015 at 10:33
  • Thanks for your hint. I must say though that this does not address my question, which is about choosing the initially selected value.
    – Antonio
    Commented Oct 8, 2015 at 12:08
  • 1
    Have you read the other answer? :) It explains why I was not able to choose the initially selected value (in my form's constructor).
    – Antonio
    Commented Oct 8, 2015 at 13:08
  • I know that this was the problem of your Binding method. I was just showing how easy it would be to avoid binding and what the advantages would be if in near future you need more than just an int-string pair. Consider the changes needed in both method. Consider which method would be easier to understand for someone who hasn't seen your code yet. Which method seems like magic and which one seems like the natural way to solve it. Commented Oct 9, 2015 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.