/ Published in: C#
This example shows how to bind a combobox to a list of value-name pairs. Selecting a value results in the appropriate text being displayed. This example uses both a Dictionary and an enum.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Create a dictionary with value-name pairs. This will be bound to comboBox1 { { 100, "Arthur"}, { 200, "Ford" }, { 300, "Trillian"}, { 400, "Zaphod"}, }; // Create an enum. This will be bound to comboBox2 public enum MyEnumType { Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6, } // In the form Load event, bind the combobox to the data source. private void Form1_Load(object sender, EventArgs e) { // Bind comboBox1 and set a default. comboBox1.DisplayMember = "Value"; comboBox1.ValueMember = "Key"; comboBox1.SelectedValue = 300; // Bind comboBox2 and set a default. comboBox2.SelectedItem = MyEnumType.Friday; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { label1.Text = Convert.ToString(comboBox1.SelectedValue); // Initially shows "300" while combo shows "Trillian". } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { label2.Text = Convert.ToString((int)comboBox2.SelectedItem); // Initially shows "5" while the combo shows "Friday". }
URL: http://madprops.org/blog/bind-a-combobox-to-a-generic-dictionary/