Bind arrays and lists in C#

[bind arrays]

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 Example   Follow me on Twitter   RSS feed   Donate








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

2 Responses to Bind arrays and lists in C#

  1. raghu says:

    List animal_list = new List();
    should be
    List animal_list = new List();

    May be Type not mentioned for users to figure it out. ­čÖé

  2. Rod Stephens says:

    Sorry about that. The blog gets confused if the the code contains pointy brackets and this code included <string>. I’ve fixed it now. Thanks for pointing this out!

Leave a Reply

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