views:

312

answers:

1

I have the following classes:

public class MyItems : List<MyItem>
{
...
}

public class MyItem
{
...
}

I've instantiated MyItems and assigned it to the DataSource property of a WinForms datagrid.

Everything displays properly, but when I try to add rows, nothing happens. What I do is case the grids DataSource back to MyItems, add an instance of MyItems to it, and then set the DataSource back to the list. I can step through the code and see that the count of items in the datasource is growing, but the grid isn't displaying them. Any ideas?

//Form Load
MyItems lstItems = new MyItems();
lstItems.Add(new MyItem("1"));
lstItems.Add(new MyItem("2"));

//Grid displays two rows;
grd.DataSource = lstItems;

//Add button click event
MyItems lstItmes = (MyItems)grd.DataSource;
lstItems.Add(new MyItem("3"));

//Grid does not display new row
grd.DataSource = lstItems;
+3  A: 

In order for changes to the data source to show up, it must implement the System.ComponentModel.IBindingList interface. This is the interface that provides the ListChanged event, which is what the grid hooks into in order to discover changes to the list (adding and removing items) or to rows (changing property values).

Additionally, the ITypedList interface is what allows the designer to discover properties and how the grid can perform data binding with better performance than reflection-based binding.

If you're just looking for basic notifications and your base class already inherits from something like List<T>, try changing the parent to System.ComponentModel.BindingList<T>. This has a simple implementation of the IBindingList interface already. You'll have to do more work if you want more advanced things like sorting or support property change notification, but it provides the implementation for basic adding and removing.

Adam Robinson