Reputation: 394
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
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:
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
Reputation: 1856
You can set it by column number as follows,
// Make fourth column not sortable
dataGridView1.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;
Upvotes: 0