Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

5. Windows Forms Datagrid

5.48 How can I prevent my user from sizing columns in my datagrid?


You can do this by subclassing your grid and overriding OnMouseMove, and not calling the baseclass if the point is on the columnsizing border.

[C#]
public class MyDataGrid : DataGrid
{
     protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
     {
          DataGrid.HitTestInfo hti = this.HitTest(new Point(e.X, e.Y));
          if(hti.Type == DataGrid.HitTestType.ColumnResize)
          {
               return; //no baseclass call
          }
          base.OnMouseMove(e);
     }
}

[VB.NET]
Public Class MyDataGrid
      Inherits DataGrid
     Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)
          Dim hti As DataGrid.HitTestInfo = Me.HitTest(New Point(e.X,e.Y))
          If hti.Type = DataGrid.HitTestType.ColumnResize Then
               Return 'no baseclass call
          End If
          MyBase.OnMouseMove(e)
     End Sub
End Class

The above code prevents the sizing cursor from appearing, but as Stephen Muecke pointed out to us, if the user just clicks on the border, he can still size the column. Stephen's solution to this problem is to add similar code in an override of OnMouseDown.

[C#]
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
     DataGrid.HitTestInfo hti = this.HitTest(new Point(e.X, e.Y));
     if(hti.Type == DataGrid.HitTestType.ColumnResize)
     {
          return; //no baseclass call
     }
     base.OnMouseDown(e);
}

[VB.NET]
Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
     Dim hti As DataGrid.HitTestInfo = Me.HitTest(New Point(e.X,e.Y))
     If hti.Type = DataGrid.HitTestType.ColumnResize Then
          Return 'no baseclass call
     End If
     MyBase.OnMouseDown(e)
End Sub