Pieter
Pieter

Reputation: 32805

Quickest way to display a List<String> in a WinForms app?

I'm fairly new to Visual C# and I'm trying to create a List<String> whose contents are shown by a form widget, preferably using the form editor. Coming from a Qt/C++ background I usually do something like this:

This procedure is a pain in the butt and I'm sure that there's a better way, but I'm not here for Qt help right now. What's the quickest way to display the contents of a List<String> (or similar structure) in C#? I'm using WinForms.

Upvotes: 5

Views: 19645

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273554

// simple one-way, one-time binding 
var myItems = new List<string> { "aaa", "bbb" };
listBox1.DataSource = myItems;
// rebinding
var myItems = new List<string> { "aaa", "bbb" };
listBox1.DataSource = myItems;
....
myItems.Add("ccc");
listBox1.DataSource = myItems;
// one-way, multi-time binding
var myItems = new BindingList<string> { "aaa", "bbb" };
listBox1.DataSource = myItems;
...
myItems.Add("ccc");

Upvotes: 8

Related Questions