简体   繁体   English

如何禁用 Datagrid 中的特定列排序?

[英]How to disable specific column Sorting in Datagrid?

In winforms .Net Framework 1.1, is there any way to disable sorting on specific column in datagrid.在 winforms .Net Framework 1.1 中,有没有办法禁用对数据网格中特定列的排序。

If I try to set Allow sorting equal to false, then it disable sorting in all columns.如果我尝试将允许排序设置为 false,则它会禁用所有列中的排序。 But I need to disable specific columns in the datagrid.但我需要禁用数据网格中的特定列。

this.dataGrid1.AllowSorting = false;

DataGrid control doesn't have a property to control sorting of columns separately. DataGrid控件没有单独控制列排序的属性。 You can just allow or disallow sorting of all columns by setting AllowSorting .您可以通过设置AllowSorting来允许或禁止对所有列进行AllowSorting

But looking into source code of the control , the control performs sorting by handling mouse up, by hit-testing to check if the mouse up if happening on column header.但是查看控件的源代码,控件通过处理鼠标向上执行排序,通过点击测试来检查鼠标是否在列标题上发生。 So to customize the behavior, you can override OnMouseUp and fool the base method by passing a fake mouse event args:因此,要自定义行为,您可以覆盖OnMouseUp并通过传递假鼠标事件参数来欺骗基本方法:

public class MyDataGrid : DataGrid
{
    protected override void OnMouseUp(MouseEventArgs e)
    {
        var hti = HitTest(e.X, e.Y);
        var newArgs = new MouseEventArgs(e.Button, e.Clicks, -1, -1, e.Delta);
        if (hti.Type == HitTestType.ColumnHeader && hti.Column == 0)
            base.OnMouseUp(newArgs);
        else
            base.OnMouseUp(e);
    }
}

Then you can use MyDataGrid control on form:然后你可以在表单上使用MyDataGrid控件:

在此处输入图片说明

You can enhance the code example and add a property to contain a list of sortable or non-sortable properties and instead of hti.Column == 0 check for those sortable/non-sortable column indices.您可以增强代码示例并添加一个属性以包含可排序或不可排序的属性列表,而不是hti.Column == 0检查那些可排序/不可排序的列索引。

You can set it by column number as follows,您可以按列号进行设置,如下所示,

// Make fourth column not sortable
dataGridView1.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM