Q
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
    CenterButton()
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
    CenterButton()
End Sub
This was last published in November 2003

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Join the conversation

1 comment

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

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)
Next
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.
Cancel

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

TheServerSide

SearchCloudApplications

Close