Datagridview shall disappear when clicking on the

2019-01-29 00:26发布

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?

3条回答
干净又极端
2楼-- · 2019-01-29 01:02

The Leave event will not raise if you click on Form, or a ToolStripButton, PictureBox or any other non-selectable control.

If you expect a behavior like a dropdown, you can host DataGridView in a ToolStripControl host and show it using a ToolStripDropDown. 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:

private void button1_Click(object sender, EventArgs e)
{
    this.dataGridView1.Margin = new Padding(0);
    var host = new ToolStripControlHost(this.dataGridView1);
    this.dataGridView1.MinimumSize = new Size(200, 100);
    host.Padding = new Padding(0);
    var dropdown = new ToolStripDropDown();
    dropdown.Padding = new Padding(0);
    dropdown.Items.Add(host);
    dropdown.Show(button1, 0,button1.Height);
}

enter image description here

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.

查看更多
Melony?
3楼-- · 2019-01-29 01:02

Change the event handler assigning to:

this.dataGridView1.Leave += new System.EventHandler(fokussiert);

Worked for me when focusing on a textbox

查看更多
爷的心禁止访问
4楼-- · 2019-01-29 01:21

you want your dgv also to disapear when you click on your textbox? is that what you mean?

   private void dataGridView1_Leave(object sender, EventArgs e)
    {
        dataGridView1.Visible = false;        
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        dataGridView1.Visible = false;
    }
查看更多
登录 后发表回答