我想写的代码如下:
IEnumerable<SomeModel> items = GetTheItems();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = BuildTheDataSource(items);
数据网格会在标题上显示排序字形,并允许用户点击它们进行排序。
我迄今为止最有希望的领导是提出的by this answer 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;
}
答案 0 :(得分: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 Properties
的{{1}}创建的。
你的问题是什么意思?:
但该解决方案(和其他)似乎只适用于手动创建的列。
<强>更新强>
试试这个
Person