As described in the title, I have a Form with a Datagridview on the front. The datagridview is smaller than my form in the back and I want the Datagridview to disappear whenever I click anywhere else but the Datagridview.
My code looks like this:
this.dataGridView1.Leave += new System.EventHandler(this.focus);
and the Eventhandler is defined like this:
private void focus(object sender, EventArgs e)
{
if(dataGridView1.Focused == false)
{
dataGridView1.Visible = false;
}
}
My problem is that my Datagridview only disappears when a new event in my form is activated but not when I click for example in a textbox on my form.
Can anyone help me?
The
Leave
event will not raise if you click onForm
, or aToolStripButton
,PictureBox
or any other non-selectable control.If you expect a behavior like a dropdown, you can host
DataGridView
in aToolStripControl
host and show it using aToolStripDropDown
. This way when you click anywhere outside the `DataGridView, it will disappear. It will act like a dropdown menu. Also the grid can be larger than your form:Important Note: It's an example. It's better to pay attention to disposing of objects in a real world application. For example, use just a single
ToolStripdropDown
and dispose it when closing the form.Change the event handler assigning to:
Worked for me when focusing on a textbox
you want your dgv also to disapear when you click on your textbox? is that what you mean?