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:
How can I choose the initially selected value in a ComboBox
using as DataSource a List<KeyValuePair<int, string>>
?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With