Shadow
Shadow

Reputation: 4006

How do I center content in a Panel?

I have a panel, inside which I am trying to center the controls. But apparently, panels don't like padding when they are docked to the edge of a control. Here is the current code for my panel:

buttonPanel = new Panel();
buttonPanel.Width = 300;
buttonPanel.Height = 50;
buttonPanel.Dock = DockStyle.Bottom;
buttonPanel.Padding = new Padding((this.ClientSize.Width - buttonPanel.Width) / 2, 0,
                                 (this.ClientSize.Width - buttonPanel.Width) / 2, 0);
buttonPanel.BackColor = Color.Transparent;
this.Controls.Add(buttonPanel);

I have a single button placed inside the panel. What I would expect with the above code, is that the control is placed nicely to the left of a 300 wide "rectangle" centered in the panel. But the button is placed on the very left, as if the padding is ignored:

enter image description here

How can I center a collection of buttons to the center of my form?

Upvotes: 3

Views: 27909

Answers (2)

MahanGM
MahanGM

Reputation: 2382

Design Time Approach

At design time, put your button in your container and select your button. Then, use Center Horizontally and Center Vertically from Layout toolbar to put your button in center of panel. After, go to your buttons properties and remove every anchor from Anchor property.

Coding Approach

Panel panel = new Panel();
panel.Size = new Size(300, 100);
panel.Dock = DockStyle.Bottom;

Button button = new Button();
button.Size = new Size(70, 25);
button.Location = new Point((panel.Width - button.Width) / 2, (panel.Height - button.Height) / 2);
button.Anchor = AnchorStyles.None;

panel.Controls.Add(button);
this.Controls.Add(panel);

Upvotes: 5

t3chb0t
t3chb0t

Reputation: 18675

You have to align the button inside the panel by setting the button's position not the panel's padding:

button1.Left = (int)(panel1.Width * 0.5f - button1.Width * 0.5f);
button1.Top = (int)(panel1.Height * 0.5f - button1.Height * 0.5f);

or

button1.Location = new Point()
{
    X = panel1.Width / 2 - button1.Width / 2,
    Y = panel1.Height / 2 - button1.Height / 2
};

the result is the same.

If you override the OnResize method the button will stay centered also when you change the size of the form:

protected override void OnResize(EventArgs e)
{
    button1.Location = new Point()
    {
        X = panel1.Width / 2 - button1.Width / 2,
        Y = panel1.Height / 2 - button1.Height / 2
    };
    base.OnResize(e);
}

Upvotes: 2

Related Questions