Bind arrays and lists to ListBoxes to easily display their items in C#

One way to display the items in an array or list 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. Simply set the ListBox's DataSource property to the array or list and the ListBox displays the items automatically. It uses the items' ToString methods to figure out what to display for non-strings. This example demonstrates this 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<string> animal_list = new List<string>();
animal_list.Add("ape");
animal_list.Add("bear");
animal_list.Add("cat");
animal_list.Add("dolphin");
animal_list.Add("eagle");
animal_list.Add("fox");
animal_list.Add("giraffe");

lstArray.DataSource = animal_array;
lstCollection.DataSource = animal_list;
}

Download example


-->