0
votes

The code I would like to write would look like this:

IEnumerable<SomeModel> items = GetTheItems();

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = BuildTheDataSource(items);

And the data grid would show the sort glyphs on the headers and allow the user to sort by clicking them.

The most promising lead I've had so far was the SortableBindingList proposed by this answer, but that solution (and others) seem to work only for manually created columns.

Update

Well the egg is on my face now! The SortableBindingList does work, but I made a classic blunder:

void Bind(List<Model> items)
{
    this.items = new SortableBindingList<Model>(items);

    // oops! "items" is a List<T>... what I really wanted was
    // "this.items" which is a SortableBindingList<T>
    dataGridView1.DataSource = items;
}
1

1 Answers

0
votes

If i understand your question. The given example of SortableBindingList

is thus:

        this.dataGridView1.AutoGenerateColumns = false;

        this.ColumnId.DataPropertyName = "Id";
        this.ColumnFirstName.DataPropertyName = "FirstName";
        this.ColumnLastName.DataPropertyName = "LastName";
        this.ColumnBirthday.DataPropertyName = "Birthday";
        this.ColumnScore.DataPropertyName = "Score";

        List<Person> list = new List<Person>();
        list.Add(new Person(1, "Tim", "4", new DateTime(1980, 4, 30), 100.1));
        list.Add(new Person(2, "Amy", "2", new DateTime(1983, 1, 1), 200.2));
        list.Add(new Person(3, "Sarah", "3", new DateTime(1984, 1, 24), 300.3));
        list.Add(new Person(4, "Mike", "1", new DateTime(1988, 3, 21), 400.4));

        SortableBindingList<Person> persons = new SortableBindingList<Person>(list);

        this.dataGridView1.DataSource = persons;

so, from the List<Person> to SortableBindingList the column is created base in the Fields and Properties of the Person.

what did you mean from your question?:

but that solution (and others) seem to work only for manually created columns.

Update

Try this one

        dataGridView1.AutoGenerateColumns = true;
        IEnumerable<SomeModel> items = GetTheItems();

        SortableBindingList<SomeModel> items = new SortableBindingList<SomeModel>(items.ToList()); 
        dataGridView1.DataSource = items;