Forms controls sizing issue


Well-known member
Nov 16, 2005
Columbia, SC
Programming Experience
It seems no matter how long I do this stuff, I continually get hung up on the ridiculously small stuff. Here's the only code on a simple form that is supposed to set the width of a panel (Panel1) to be 30 pixels less than the width of the form and center it. (15 pix on each side of the panel...) Make Panel1's backcolor different so it's easy to see its size in ref to the Form size.
Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        Panel1.Width = Me.Width - 30
        Panel1.Location = New Point(CInt((Me.Width - Panel1.Width) / 2), Panel1.Location.Y)
    End Sub
After starting the project and / or resizing, Panel1's margin on the left is OK but the margin on the right is slam up against the right form border.
I have the only anchor set tot the Top, but it really doesn't matter how I set the Anchor... No padding...
I've been centering Panels, labels pictureboxes etc for years and never noticed them being off by 10 or 15 pixels.
Taking a screenshot and measuring Panel1 in another graphics program, Panel1.Width, which should have been 895 pixels in reality measured 910 pixels.
I've tried the same process with a label rather than a panel and it does exactly the same thing.
Am I just going stupid or what ?
Of course... I told you I was going stupid. Not using ClientSize is the error.
What a supreme waste of time !

The control is a DataGridView rather than a Panel.
The reason I've went this direction is because the DataGridView would not center within the form when Maximizing from a much smaller normal size when all anchors were set.

Thanks John, as always...
Last edited:
The simplest way to centre a control is to put it in a TableLayoutPanel. Add a TableLayoutPanel to the form with three columns and three rows, set the middle column and row to autosize and the others to 50% and then add a control to the centre cell, that control will then remain in the centre of the form no matter the size or aspect ratio.