Datagridview shall disappear when clicking on the Form in the background

后端 未结 3 1244
别跟我提以往
别跟我提以往 2020-12-21 23:31

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 when

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 00:01

    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);
    }
    

    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.

提交回复
热议问题