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

查看:138
本文介绍了当用户点击列标题时如何启用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.Apellidos作为默认排序,但我也想允许用户点击列标题进行排序。

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属性设置为自动

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查询,它不会被排序。因此,请浏览链接,该链接说明如何创建一个可排序的绑定列表,然后将其作为数据源提供给datagridview。

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

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

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