0

我想编写的代码如下所示:

IEnumerable<SomeModel> items = GetTheItems();

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

数据网格将在标题上显示排序字形,并允许用户通过单击它们进行排序。

到目前为止,我最有希望的线索是这个答案提出的 SortableBindingList ,但该解决方案(和其他)似乎仅适用于手动创建的列。

更新

好吧,鸡蛋现在在我脸上!SortableBindingList 确实有效,但我犯了一个典型的错误:

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;
}
4

1 回答 1

0

如果我理解你的问题。SortableBindingList的给定示例

因此是:

        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;

所以,从List<Person>SortableBindingList列是在 的 中创建Fields and PropertiesPerson

你的问题是什么意思?:

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;
于 2012-12-19T23:28:48.273 回答