You can catch clicking off a DataGrid in the DataGrid.Validated event. But this event is also hit when you use the Tab key to move around the grid. So if you want to catch it exclusively for clicking off the grid, you have to ignore the event due to the Tab. One way to do this is to derive DataGrid and override ProcessDialogKey, noting whether the key is a Tab before processing it.
public class CustomDataGrid: DataGrid
{
private bool inTabKey = false;
public bool InTabKey
{
get { return inTabKey; }
set { inTabKey = value; }
}
protected override bool ProcessDialogKey( Keys keyData )
{
inTabKey = keyData == Keys.Tab;
return base.ProcessDialogKey( keyData );
}
}
Then in your Validated event handler, you can check for this Tab. Here are some snippets.
private CustomDataGrid dataGrid1;
private void dataGrid1_Validated( object sender, EventArgs e )
{
if ( !dataGrid1.InTabKey )
Console.WriteLine( "Clicked off grid" );
else
dataGrid1.InTabKey = false;
}
Contributed from George Shepherd's Windows Forms FAQ