George Shepherd's Windows Forms FAQ
Questions and answers in this FAQ have been collected from newsgroup posts, various mailing lists and the employees of Syncfusion.

5.52 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


Windows Forms-Datagrid

© 2001-2009 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap