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

2019-02-02 03:21发布

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?

4条回答
太酷不给撩
2楼-- · 2019-02-02 03:43

Try :

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

listBox1.DataSource = MyList;

Have a look at ListControl.DataSource Property

查看更多
男人必须洒脱
3楼-- · 2019-02-02 03:46

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.

查看更多
SAY GOODBYE
4楼-- · 2019-02-02 03:47

Is this what you are looking for:

myListBox.DataSource = MyList;
查看更多
贪生不怕死
5楼-- · 2019-02-02 03:49

You can also use the AddRange method

listBox1.Items.AddRange(myList.ToArray());
查看更多
登录 后发表回答