Positioning controls at Runtime

ianlknight

New member
Joined
Feb 25, 2009
Messages
2
Programming Experience
10+
Simple question. How do you position controls loaded at runtime to align middle? I'm not looking to match the x y coordinates as the heights vary.

For example loading 2 text boxs and 2 labels.

I've tried using the Anchor and Dock properties but with no joy.
e.g.
txtNewTextBox = New TextBox
txtNewTextBox.Name = "name"
txtNewTextBox.Dock = DockStyle.Fill
txtNewTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
pnlHeader.Controls.Add(txtNewTextBox, 1, 1)
 
give this a try

VB.NET:
Public Class Form1

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

        'align the textboxes to the middle of the form 
        'the form contains a textbox of the name txtOpen
        CenterControl(txtOpen, Me.ClientSize.Width)

    End Sub

    Public Sub CenterControl(ByRef ControlToCenter As Control, ByVal FormClientSizeWidth As Integer)
        ControlToCenter.Left = (FormClientSizeWidth / 2) - (ControlToCenter.Width / 2)
    End Sub
End Class
 
demausdauth said:
Sub CenterControl(ByRef ControlToCenter As Control
Note that one rarely use ByRef for reference type parameters, as this give the method the opportunity (though caller can still force ByVal) to dereference your original variable or change the object for a different one, as opposed to ByVal where the method can only interact with the objects properties and methods.
 
Cheers fellas - I'll give that a go.

In answering my own solution. I had the controls in a tablelayoutpanel and was adding them in a loop, label, textbox etc. My thought - "Maybe" they are alligned but the text in the Labels are NOT. The solution presented itself, when adding labels I added the following:-

lblNewLabel.TextAlign = ContentAlignment.MiddleLeft

so:-
VB.NET:
txtNewTextBox = New TextBox
txtNewTextBox.Name = "txtname"
txtNewTextBox.Dock = DockStyle.Fill
txtNewTextBox.Anchor = System.Windows.Forms.AnchorStyles.None
pnlHeader.Controls.Add(txtNewTextBox, 1, 1) 
lblNewLabel.TextAlign = ContentAlignment.MiddleLeft
lblNewLabel= New TextBox
lblNewLabel.Text = "Name:"
lblNewLabel.Dock = DockStyle.Fill
lblNewLabel.Anchor = System.Windows.Forms.AnchorStyles.None
pnlHeader.Controls.Add(lblNewLabel, 1, 1)

Now all is centred, but I will try your solution as well.

Cheers
 
Back
Top