在后台单击表单时,Datagridview 将消失 [英] Datagridview shall disappear when clicking on the Form in the background
问题描述
如标题所述,我有一个前面带有 Datagridview 的表单.datagridview 比我后面的表单小,我希望 Datagridview 在我单击除 Datagridview 之外的任何其他地方时消失.
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.
我的代码如下:
this.dataGridView1.Leave += new System.EventHandler(this.focus);
Eventhandler 定义如下:
and the Eventhandler is defined like this:
private void focus(object sender, EventArgs e)
{
if(dataGridView1.Focused == false)
{
dataGridView1.Visible = false;
}
}
我的问题是我的 Datagridview 仅在表单中的新事件被激活时消失,而不是在我单击表单上的文本框时消失.
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.
有人可以帮我吗?
推荐答案
如果您单击 Form
或 ToolStripButton<,
Leave
事件不会引发/code>、PictureBox
或任何其他不可选择的控件.
The Leave
event will not raise if you click on Form
, or a ToolStripButton
, PictureBox
or any other non-selectable control.
如果您期望下拉列表之类的行为,您可以在 ToolStripControlHost
中托管 DataGridView
并使用 ToolStripDropDown
显示它.这样当你点击`DataGridView 之外的任何地方时,它就会消失.它就像一个下拉菜单.网格也可以比你的表单大:
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);
}
重要提示: 这是一个例子.在现实世界的应用程序中最好注意处理对象.例如,只使用一个 ToolStripdropDown
并在关闭表单时处理它.
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.
这篇关于在后台单击表单时,Datagridview 将消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!