OK; DataGridView, along with many other data-bound controls,
recognises a few well-known interfaces, such as IList (also
IListSource and ITypedList), IBindingList, IBindingListView,
ICancelAddNew and IRaiseItemChangedEvents. It uses these interfaces to
get the collection to do a lot of the work itself, such as reading /
editing rows, sorting, etc.
Fortunately, BindingList<T> supports *most* of the things that
DataGridView can use - but it doesn't support sorting. DataTable
(well, DataView) is another construct that supports these interfaces,
but that *does* support searching. Luckily we can extend
BindingList<T> to enable sorting on classes (rather than using DataRow
etc). This is exactly what the AdvancedList<T> [cited above] does.
Note, however, that all data-binding [what you are doing] is by
default based around properties, not fields; so here follows an
example of your class using properties with AdvancedList<T> to make a
bindable, sortable, editable table. Note that I've used C# 3 (VS2008)
syntax for brevity, but the same can be done in C# 2 (VS2005) - it
just takes a few more lines, and it is late here... Note that I haven'
re-posted AdvancedList<T>; see my previous link for that.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
static class Program
{
static void Main()
{
AdvancedList<LeadListDS> list = new
AdvancedList<LeadListDS>();
list.Add(new LeadListDS { CompanyName = "Foo", ContactName =
"Fred", StateOrProvince = "Arizona", LeadGUID = "0x000" });
list.Add(new LeadListDS { CompanyName = "Bar", ContactName =
"Jojo", StateOrProvince = "Boston", LeadGUID = "0x001" });
Application.EnableVisualStyles();
Application.Run(new Form {
Controls = {
new DataGridView {
Dock = DockStyle.Fill,
DataSource = list
}
}
});
}
}
public class LeadListDS
{
[Browsable(false)]
public string LeadGUID { get; set; }
[DisplayName("Contact Name")]
public string ContactName { get; set; }
[DisplayName("Company Name")]
public string CompanyName { get; set; }
[DisplayName("State / Province")]
public string StateOrProvince { get; set; }
// ... [snip more props]
public LeadListDS() {}
}
Marc