用户单击列标题时如何启用 DataGridView 排序? [英] How to enable DataGridView sorting when user clicks on the column header?

查看:25
本文介绍了用户单击列标题时如何启用 DataGridView 排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单上有一个 datagridview,我用这个填充它:

I have a datagridview on my form and I populate it with this:

dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
                                   .OrderBy(s => s.Apellidos)
                                   .ToList();

现在,我使用 s.Apelidos 作为默认排序,但我也希望允许用户在单击列标题时进行排序.

Now, I use the s.Apellidos as the default sort, but I'd also like to allow users to sort when clicking on the column header.

这种类型不会以任何方式修改数据,这只是一个客户端奖励,可以在用眼睛扫描屏幕时更容易地搜索信息.

This sort will not modify the data in any way, it's just a client side bonus to allow for easier searching for information when scanning the screen with their eyes.

感谢您的建议.

推荐答案

将所有列(可由用户排序)的 SortMode 属性设置为 Automatic

Set all the column's (which can be sortable by users) SortMode property to Automatic

dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
                                   .OrderBy(s => s.Apellidos)
                                   .ToList();

    foreach(DataGridViewColumn column in dataGridView1.Columns)
    {
    
        column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

由于您的 datagridview 与 linq 查询绑定,因此不会对其进行排序.所以请仔细阅读这个 [404 dead link, see next section] ,它解释了如何创建一个可排序的绑定列表,然后将它作为数据源提供给 datagridview.

As your datagridview is bound with a linq query, it will not be sorted. So please go through this [404 dead link, see next section] which explains how to create a sortable binding list and to then feed it as datasource to datagridview.

上面的链接是 404-dead.我从 Internet Wayback Machine 归档页面.

Link from above is 404-dead. I recovered the code from the Internet Wayback Machine archive of the page.

public Form1()
{
    InitializeComponent();

    SortableBindingList<person> persons = new SortableBindingList<person>();
    persons.Add(new Person(1, "timvw", new DateTime(1980, 04, 30)));
    persons.Add(new Person(2, "John Doe", DateTime.Now));

    this.dataGridView1.AutoGenerateColumns = false;
    this.ColumnId.DataPropertyName = "Id";
    this.ColumnName.DataPropertyName = "Name";
    this.ColumnBirthday.DataPropertyName = "Birthday";
    this.dataGridView1.DataSource = persons;
}

这篇关于用户单击列标题时如何启用 DataGridView 排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆