Ammar Ahmed Ammar Ahmed - 17 days ago 7
C# Question

Created two buttons but only able to center one

i've searched stack overflow but un able to get the exact answer..

i'm doing a school assignment in which i've created two buttons using C# console application not windows form application..now i want to center both of them i'm able to center one of them but not both

this is how i centered my first button but how i can center both of them ?

Button btn_1 = new Button();
btn_1.Parent = this;
btn_1.Location = new Point(
(ClientSize.Width - btn_1.Width) / 2,
(ClientSize.Height - btn_1.Height) / 2
);
btn_1.Text = "some text";


in this way i can center only one button how to center both of them... if i use the same code then they will overlap but how to make both of them appear exactly in center

Answer

If the Layout is above each other, then you can take the first Button as reference. Specify the Y-coordinate of the second Button as the (Y-Position + the height) of Button 1:

Button btn_1 = new Button();
btn_1.Parent = this;
btn_1.Location = new Point(
    (ClientSize.Width - btn_1.Width) / 2,
    (ClientSize.Height - btn_1.Height) / 2
);
btn_1.Text = "some text";

this.Controls.Add(btn_1);

Button btn_2 = new Button();
btn_2.Parent = this;

// here use the coordinates of the first button
btn_2.Location = new Point(btn_1.Location.X,
    btn_1.Location.Y + btn_1.Height  // position it below the first button
    );

btn_2.Text = "2";

this.Controls.Add(btn_2);

This code will place the second button below the first.

EDIT:

If you want both buttons also centred on the Y-Axis you need to move the first button 1 button-height unit upwards like this:

btn_1.Location = new Point(
    (ClientSize.Width - btn_1.Width) / 2,
    (ClientSize.Height - btn_1.Height * 2) / 2 // subtract 2 * the height!
);

Subtract 2 * the height because you have 2 buttons

Comments