Live Chat Icon For mobile
Live Chat Icon

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

Platform: WinForms| Category: 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

Share with

Related FAQs

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

Please submit your question and answer.