C#•Improve the DataGrid

Listing 1. This class overrides the default double-click of the DataGrid control that ships with Visual Studio .NET. This augmented version of the class hooks events fired by the column controls automatically by binding to them whenever they get added. This version provides an experience more consistent with what users expect from a Windows control when they double-click on it.

public class MyDataGrid : DataGrid
{
	// Field use to memorize the last click time
	private DateTime timeGridClick;

	protected override void 
		OnMouseDown(MouseEventArgs e)
	{
		// Memorizes the first click time
		this.timeGridClick = DateTime.Now;
		base.OnMouseDown(e);
	}

	// New event
	public event System.EventHandler 
		GridDoubleClick;

	protected void OnControlMouseDown( 
		object sender, MouseEventArgs e)
	{
		// We check whether the last click was 
		// within the double-click period
		if(DateTime.Now < 
			this.timeGridClick.AddMilliseconds( 
			SystemInformation.DoubleClickTime))
		{
		// A double-click, so fire the event!
			if (this.GridDoubleClick != null)
			{
			this.GridDoubleClick(this,new 					System.EventArgs());
			}
		}
	}

	protected override void 
		OnControlAdded(ControlEventArgs e)
	{
		base.OnControlAdded(e);

		// Fires the OnControlMouseDown handler 
		// whenever a column is clicked
		e.Control.MouseDown += new 
			MouseEventHandler( 
			this.OnControlMouseDown);
	}
}