views:

208

answers:

2

I've adopted the following pattern for putting ListViewItems in a ListView with multiple columns (when I want to display information about a list of MyObject types), and I'm just curious to see if this is the best way to accomplish this task, or if there's anything more efficient and readable in code:

  1. Create an inherited ListViewItem class that takes a MyObject object in the constructor - I'll call this MyObjectListViewItem - and a Refresh() method that clears and re-populates the ListViewItem subitems.
  2. Populate the ListView with my new MyObjectListViewItem items.

example:

public MyObject MyObject { get; set; }
public MyObjectListViewItem(MyObject myObj)
{
    MyObject = myObj;
    this.Refresh();
}

public void Refresh()
{
 this.SubItems.Clear();
 this.Text = myObj.FirstColumnProperty;
 this.SubItems.Add(myObj.SecondColumnProperty); // etc...
}

Suggestions? Better ways?

+2  A: 

Have you considered using a BindingSource, or creating your own which implements IBindingListView? This keeps concerns about the data and its state scoped to the data itself and not on any controls which consume it. Since .NET controls are already built to work with BindingSources, you can take advantage of some more robust functionality. Instead of explicitly invoking a screen refresh, the control is simply responsible for responding to events raised by the binding source, and a controller that notifies whether the control is ready to be refreshed without forcing it.

Rex M
This will not work. ListViews under WinForms do NOT support BindingSources.
Grammarian
A: 

Making ListViewItems that know how to build themselves is a good idea.

If you extend that idea a little, you make the columns know how to build each subitem, which also allows them to be able to automatically sort the ListView, support grouping and copy/drag and drop rows. This is just a few of the things that ObjectListView does for you.

ObjectListView is an open source wrapper around a .NET WinForms ListView control that makes the ListView much easier to use -- as well as adding some very nice new features and getting around some annoying bugs/limitations.

Simple ObjectListView in action

If you did like @Rex's idea of using a BindingSource, the ObjectListView project also provides a data-aware DataListView which is data bindable.

Grammarian