Emory Lu
Emory Lu

Reputation: 77

How to add button to a specific DataGridView C# WinForms

enter image description here

Hi, I am very new to C# and WinForms. Just like this image showing, I added DataGridView_B to DataGridView_A, where DataGridView_B is usually invisible and only be visible when certain function is called. As far to this step, everything works well. Then I decided to add a button Button_Close to DataGridView_B, so when I don't need DataGridView_B, I can click the button and it would be invisible again.

Code that I used to bound B to A, which works fine:

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

Code that I used to bound button to B, which has issue:

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

As long as I bound button to B, the button disappears, then I tried to comment out this line of code, the button is still gone.

Does anyone have any thoughts about why the code acts like this?

Note: the button is added manually by the Toolbox, not programmatically.

Upvotes: 0

Views: 360

Answers (1)

Nova_
Nova_

Reputation: 88

When you drop items in from the Toolbox instead of programmatically adding them, their location is absolute to the top left corner of the form.

In your example, I'll make the following assumptions:

DataGridView_A is 400 x 800 px.
DataGridView_B is 400 x 300 px.
Button_Close is at Point (350, 510). (Relative to top left corner of form)

When you programmatically add Button_Close to DataGridView_B, the location of the button is persevered but in the wrong way. It keeps the Point (350, 510) and not the Point relative to DataGridView_B. This puts Button_Close at Point (350, 510) relative to DataGridView_B when you add it, thus it is not in view.

This can be fixed by adding the button and moving its location to your desired location. Example:

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

Upvotes: 3

Related Questions