Link data sources between ComboBoxes and ListBoxes in C#

Few people know that you can set a ComboBox's or ListBox's DataSource property to an array or other object holding values and it will display those values. This can be a convenient way to make one of these controls display a set of values generated in code.

Even fewer people realize that the data source array has a notion of a selected item. that means if you use the same array as a data source for multiple ComboBoxes and ListBoxes, then they all remain synchronized. If you select an item in one of the controls, all of the others select it, too.

This example uses the following code to initialize its controls.

// Display some values.
private void Form1_Load(object sender, EventArgs e)
{
string[] values = { "Aardvark", "Bear", "Cat", "Dog" };
comboBox1.DataSource = values;
comboBox2.DataSource = values;
listBox1.DataSource = values;
listBox2.DataSource = values;
}

The code makes an array of strings and then assigns it to each of the controls' DataSource properties. If you select an item in one control, the other controls all select the same item.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.