Title: Bind arrays and lists in C#
One way to display the items in an array in a ListBox is to loop through the items and add them to the ListBox one at a time, but there's an easier way. You can bind arrays to a ListBox by setting the ListBox control's DataSource property to the array. The ListBox uses the items' ToString methods to figure out what to display for non-strings.
The same trick works for lists or for any object that implements IList or IListSource.
This example binds arrays and lists with the following code.
// Display data in the ListBoxes.
private void Form1_Load(object sender, EventArgs e)
{
string[] animal_array = { "ape", "bear", "cat",
"dolphin", "eagle", "fox", "giraffe" };
List animal_list = new List(animal_array);
lstArray.DataSource = animal_array;
lstList.DataSource = animal_list;
}
This code initializes an array of strings. It then creates a List<string>, passing the constructor the array. That creates and initializes the list with the same items that are in the array.
The code then sets the DataSource properties for its two ListBox controls to the array and the list.
Note that you cannot add items to a ListBox that is bound to a data source.
Download the example to experiment with it and to see additional details.
|