Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

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:

  • Create a custom data structure in my Model that wraps around a QList<string> and derives from the Subject class in the Observer pattern.
  • Create a new widget that subclasses from Observer (which again is part of the Observer pattern) and one of Qt's list widgets. This newly created widget should be able to update the list when it receives a notification from the data structure.
  • Make sure that the widget subscribes to the data structure at runtime.

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.

like image 288
Pieter Avatar asked Feb 18 '23 22:02

Pieter


1 Answers

// 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");
like image 143
Henk Holterman Avatar answered Mar 04 '23 20:03

Henk Holterman