I had it in my mind that if I implemented INotifyCollectionChanged on my Custom Collection that the DataGridView would subscribe to the CollectionChanged event.
My Collection implements IListSource and INotifyCollectionChanged, and has an internal BindingList. I subscribe to the ListChanged event from the BindingList and call my OnCollectionChanged method which then raises the CollectionChanged event.
Perhaps there is a better way to accomplish the above, and I would be glad to hear it. However, my primary concern at the moment is getting the DataGridView to update after this sort method is called:
public void Sort(List<SortField> sortFields)
{
if(sortFields == null || sortFields.Count == 0) return;
IOrderedEnumerable<T> res;
if (sortFields[0].Ascending)
res = _items.OrderBy(o => o[sortFields[0].Name]);
else
res = _items.OrderByDescending(o => o[sortFields[0].Name]);
for (int x = 1; x < sortFields.Count; x++)
if (sortFields[x].Ascending)
res = res.ThenBy(o => o[sortFields[x].Name]);
else
res = res.ThenByDescending(o => o[sortFields[x].Name]);
Items = new BindingList<T>(res.ToList());
OnListChanged(this, new ListChangedEventArgs(ListChangedType.Reset, null));
}
Am I mistaken in my belief that the DataGridView subscribes to the CollectionChanged event or am I doing something else wrong?
I assume you are using ObservableCollection<T>
class for your custom collection. DataGridView
doesn't know about INotifyCollectionChanged
. It is intended for WPF bindings and not to be used in WinForms
.
See this SO question for more information.