简体   繁体   中英

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.

If I try to set Allow sorting equal to false, then it disable sorting in all columns. 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. You can just allow or disallow sorting of all columns by setting 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:

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:

在此处输入图片说明

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.

You can set it by column number as follows,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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