Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing initially selected value for a ComboBox with a List of KeyValuePair as DataSource

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>>?

like image 256
Antonio Avatar asked Sep 23 '15 21:09

Antonio


1 Answers

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);
}
like image 133
LarsTech Avatar answered Oct 28 '22 07:10

LarsTech