Live Chat Icon For mobile
Live Chat Icon

How do I prevent sorting a single column in my DataGrid

Platform: WinForms| Category: Datagrid

You can do this by deriving the DataGrid and overriding OnMouseDown. In your override, do a HitText and if the hit is on a column header that you do not want to sort, do not call the baseclass. Here is a code that sorts all columns except the second column.


[C#] 
//derived class 
public class MyDataGrid : DataGrid
{
    protected override void OnMouseDown(MouseEventArgs e)
    {
        Point pt = new Point(e.X, e.Y);
        DataGrid.HitTestInfo hti = this.HitTest(pt);
        if (hti.Type == HitTestType.ColumnHeader && hti.Column == 1)
        {
            //don't sort col 1 
            return; //don't call baseclass 
        }
        base.OnMouseDown(e);
    }
}

[VB.NET] 
'derived class 
Public Class MyDataGrid
    Inherits DataGrid
    Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
    Dim pt As New Point(e.X, e.Y)
    Dim hti As DataGrid.HitTestInfo = Me.HitTest(pt)
        If hti.Type = HitTestType.ColumnHeader AndAlso hti.Column = 1 Then
    'don't sort col 1 
    Return 'don't call baseclass
        End If
        MyBase.OnMouseDown(e)
    End Sub 'OnMouseDown 
End Class 'MyDataGrid

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.