Link ComboBox and ListBox data sources in C#

[data sources]

Few people know that you can link ComboBox and ListBox controls to data sources. If you set their DataSource property to an array or other object holding values, the control 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 those data sources have a notion of a currently selected item. that means if you use the same array as a data source for multiple ComboBox and ListBox controls, 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 control selects the same item.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in arrays, controls, database and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.