Return to Snippet

Revision: 31735
at September 11, 2010 07:11 by jimfred


Updated Code
// Create a dictionary with value-name pairs. This will be bound to comboBox1
public static Dictionary<int, string> choices = new Dictionary<int, string>() 
{
   { 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.DataSource = new BindingSource(choices, null); 
   comboBox1.DisplayMember = "Value"; 
   comboBox1.ValueMember = "Key";
   comboBox1.SelectedValue = 300;

   // Bind comboBox2 and set a default.
   comboBox2.DataSource = Enum.GetValues(typeof(MyEnumType));
   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".
}

Revision: 31734
at September 11, 2010 06:34 by jimfred


Updated Code
public static Dictionary<char, string> choices = new Dictionary<char, string>() 
{
   { 'A', "Arthur"},
   { 'F', "Ford" },
   { 'T', "Trillian"},
   { 'Z', "Zaphod"}, 
};


// In the form Load event handler...

   // Bind the dictionary to the list of value-name pairs.
   comboBox1.DataSource = new BindingSource(choices, null); 
   comboBox1.DisplayMember = "Value"; 
   comboBox1.ValueMember = "Key";

   comboBox1.SelectedValue = 'T'; // Select a default.

Revision: 31733
at September 11, 2010 06:32 by jimfred


Initial Code
public static Dictionary<char, string> choices = new Dictionary<char, string>() 
{
   { 'A', "Arthur"},
   { 'F', "Ford" },
   { 'T', "Trillian"},
   { 'Z', "Zaphod"}, 
};


// In the form Load event handler...

   comboBox1.DataSource = new BindingSource(choices, null); 
   comboBox1.DisplayMember = "Value"; 
   comboBox1.ValueMember = "Key";

   comboBox1.SelectedValue = 'T'; // Select a default.

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

Initial Description
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.

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

Initial Tags


Initial Language
C#