How can I catch when the user clicks off the grid, say to close the form

Platform: WinForms| Category: Datagrid

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. Then in your Validated event handler, you can check for this
tab. Here are some snippets.

[C#]
//the handler that checks the derived grid’s field inTabKey
private void dataGrid1_Validated(object sender, System.EventArgs e)
{
	if(!this.dataGrid1.inTabKey)
	{
		Console.WriteLine( 'Clicked off grid');
	}
	else
		this.dataGrid1.inTabKey = false;
}

//derived class
public class MyDataGrid: DataGrid
{
	public bool inTabKey = false;

	protected override bool ProcessDialogKey(System.Windows.Forms.Keys
keyData)
	{
		inTabKey = keyData == Keys.Tab;
		return base.ProcessDialogKey( keyData);
	}
}

[VB.NET]
 ’the handler that checks the derived grid’s field inTabKey
Private Sub dataGrid1_Validated(sender As Object, e As System.EventArgs)
	If Not Me.dataGrid1.inTabKey Then
		Console.WriteLine('Clicked off grid')
	Else
		Me.dataGrid1.inTabKey = False
	End If
End Sub ’dataGrid1_Validated

’derived class
Public Class MyDataGrid
	Inherits DataGrid

	Public inTabKey As Boolean = False
     
	Protected Overrides Function ProcessDialogKey(keyData As System.Windows.Forms.Keys) As Boolean
		nTabKey = keyData = Keys.Tab
		Return MyBase.ProcessDialogKey(keyData)
	End Function ’ProcessDialogKey
End Class ’MyDataGrid

Share with

Related FAQs

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

Please submit your question and answer.