Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c# - Datagridview shall disappear when clicking on the Form in the background

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ToolStripControlHost 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...