BLOG.CSHARPHELPER.COM: Bind arrays and lists to ListBoxes to easily display their items in C#
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");
4/16/2011 12:17 AM
raghu wrote:
List animal_list = new List(); should be List animal_list = new List();
May be Type not mentioned for users to figure it out. :) Reply to this
4/16/2011 7:44 AMRod Stephens wrote:
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! Reply to this
List animal_list = new List();
should be
List animal_list = new List();
May be Type not mentioned for users to figure it out. :)
Reply to this
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!
Reply to this