C#, Bind a list of value-name pairs to a combobox


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // Create a dictionary with value-name pairs. This will be bound to comboBox1
  2. public static Dictionary<int, string> choices = new Dictionary<int, string>()
  3. {
  4. { 100, "Arthur"},
  5. { 200, "Ford" },
  6. { 300, "Trillian"},
  7. { 400, "Zaphod"},
  8. };
  9.  
  10. // Create an enum. This will be bound to comboBox2
  11. public enum MyEnumType
  12. {
  13. Sunday=0,
  14. Monday=1,
  15. Tuesday=2,
  16. Wednesday=3,
  17. Thursday=4,
  18. Friday=5,
  19. Saturday=6,
  20. }
  21.  
  22. // In the form Load event, bind the combobox to the data source.
  23. private void Form1_Load(object sender, EventArgs e)
  24. {
  25. // Bind comboBox1 and set a default.
  26. comboBox1.DataSource = new BindingSource(choices, null);
  27. comboBox1.DisplayMember = "Value";
  28. comboBox1.ValueMember = "Key";
  29. comboBox1.SelectedValue = 300;
  30.  
  31. // Bind comboBox2 and set a default.
  32. comboBox2.DataSource = Enum.GetValues(typeof(MyEnumType));
  33. comboBox2.SelectedItem = MyEnumType.Friday;
  34. }
  35.  
  36. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  37. {
  38. label1.Text = Convert.ToString(comboBox1.SelectedValue); // Initially shows "300" while combo shows "Trillian".
  39. }
  40.  
  41. private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
  42. {
  43. label2.Text = Convert.ToString((int)comboBox2.SelectedItem); // Initially shows "5" while the combo shows "Friday".
  44. }

URL: http://madprops.org/blog/bind-a-combobox-to-a-generic-dictionary/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.