Craig Johnston
Craig Johnston

Reputation: 5563

C#: easiest way to populate a ListBox from a List

If I have a list of strings, eg:

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

Is there an easy way to populate a ListBox using the contents of MyList?

Upvotes: 47

Views: 161627

Answers (4)

Adriaan Stander
Adriaan Stander

Reputation: 166326

Try :

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

listBox1.DataSource = MyList;

Have a look at ListControl.DataSource Property

Upvotes: 90

ShriB
ShriB

Reputation: 24

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

Upvotes: 0

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

You can also use the AddRange method

listBox1.Items.AddRange(myList.ToArray());

Upvotes: 31

Dienekes
Dienekes

Reputation: 1548

Is this what you are looking for:

myListBox.DataSource = MyList;

Upvotes: 12

Related Questions