Problem solve Get help with specific problems with your technologies, process and projects.

How do you center controls on a form in VB.NET?

Help! I'm just getting back into programming. I thought I would go with the new VB.NET versus the VB 6.0 that I was used to. How in the world do you center controls on a form in VB.NET? VB6 makes it easy with the screen.width formulas.

All the same properties are still there. Here's the code that shows how to keep a button control named buttonMain centered in a form:

Private Sub Form1_Load(ByVal sender As System.Object, _
                       ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub CenterButton()
    buttonMain.Top = (Me.ClientSize.Height/2) - (buttonMain.Height / 2)
    buttonMain.Left = (Me.ClientSize.Width/2) - (buttonMain.Width / 2)
    End Sub

Private Sub Form1_Resize(ByVal sender As Object, _
                     ByVal e As System.EventArgs) Handles MyBase.Resize
End Sub

Dig Deeper on Win Development Resources

Join the conversation

1 comment

Send me notifications when other members comment.

Please create a username to comment.

Rather than having a sub for each control, you can simply pass the control you wish to center. When I was looking to center, I was thinking of horizontally centered. Here's my version of the code above.

Private Sub hCenterControls(ByVal ctrl As Control)
ctrl.Left = (Me.ClientSize.Width / 2) - (ctrl.Width / 2)
End Sub

Private Sub hCenterControls(ByVal ctrls As ControlCollection)
For Each ctrl As Control In ctrls
ctrl.Left = (Me.ClientSize.Width / 2) - (ctrl.Width / 2)
End Sub

Granted, centering a group of controls can get messy. You'd have to write additional code to prevent controls from being on top of each other. In other words, keep the same amount of space that had between each other before you moved them.