Vignesh Nethaji
Vignesh Nethaji

Reputation: 394

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;

Upvotes: 3

Views: 2899

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125312

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.

Upvotes: 2

Abhilash Ravindran C K
Abhilash Ravindran C K

Reputation: 1856

You can set it by column number as follows,

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

Upvotes: 0

Related Questions