[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Link ComboBox and ListBox data sources in C#

[Link ComboBox and ListBox data sources in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.