繁体   English   中英

如何将按钮添加到特定的 DataGridView C# WinForms

[英]How to add button to a specific DataGridView C# WinForms

在此处输入图像描述

您好,我是 C# 和 WinForms 的新手。 就像这个图像显示的那样,我将DataGridView_B添加到DataGridView_A ,其中DataGridView_B通常是不可见的,只有在调用某些 function 时才可见。 到目前为止,一切正常。 然后我决定向DataGridView_B添加一个按钮Button_Close ,这样当我不需要DataGridView_B时,我可以单击该按钮,它会再次不可见。

我用来将 B 绑定到 A 的代码,效果很好:

this.DataGridView_A.Controls.Add(this.DateGridView_B);
...
this.DateGridView_B.Dock = System.Windows.Forms.DockStyle.Bottom;

我用来将按钮绑定到 B 的代码有问题:

this.DataGridView_B.Controls.Add(this.Button_Close);

只要我把button绑定到B,button就消失了,然后我试着把这行代码注释掉,button还是没了。

有没有人对代码为何如此行事有任何想法?

注意:该按钮是由Toolbox手动添加的,而不是以编程方式添加的。

当您从Toolbox中拖放项目而不是以编程方式添加它们时,它们的位置绝对位于窗体的左上角。

在您的示例中,我将做出以下假设:

DataGridView_A为 400 x 800 像素。
DataGridView_B为 400 x 300 像素。
Button_Close位于Point (350, 510)。 (相对于表格的左上角)

当您以编程方式将Button_Close添加到DataGridView_B时,按钮的位置会保留但方式错误。 它保留Point (350, 510) 而不是相对于DataGridView_BPoint 当您添加它时,这会将Button_Close置于相对于DataGridView_BPoint (350, 510),因此它不在视图中。

这可以通过添加按钮并将其位置移动到您想要的位置来解决。 例子:

//Add DataGridView_B to DataGridView_A
this.DataGridView_A.Controls.Add(this.DataGridView_B);
this.DataGridView_B.Dock = DockStyle.Bottom;

//Add Button_Close to DataGridView_B
this.DataGridView_B.Controls.Add(this.Button_Close);
//10 px margin on top and right
this.Button_Close.Location = new Point(this.DataGridView_B.Width - (this.Button_Close.Width + 10), 10); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM