How to disable specific column Sorting in Datagrid?

2.6k views Asked by At

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;
2

There are 2 answers

3
Reza Aghaei On BEST ANSWER

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:

enter image description here

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.

1
Abhilash Ravindran C K On

You can set it by column number as follows,

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