hi guys, just wondering is it possible to set all the textbox align to center within a form using just only one line of code?
Rather than using

123TextBox.TextAlign = HorizontalAlignment.Center
456TextBox.TextAlign = HorizontalAlignment.Center

for every Textbox.

Thanks.

Recommended Answers

All 2 Replies

not one line of code... but a subroutine to do all textboxes. And you can make it global so it can be called from Any Form.

Add a new code module to your project. Add the following code to the module:

Public Sub SetTextBoxAlignment(ByRef TargetForm As Form, ByVal tbAlignment As Windows.Forms.HorizontalAlignment, Optional ByRef WatchForExceptions As Boolean = False)

        For Each ctlOnForm As Control In TargetForm.Controls
            If TypeOf ctlOnForm Is TextBox Then
                Dim tmpTB As TextBox = DirectCast(ctlOnForm, TextBox)


                If String.IsNullOrEmpty(tmpTB.Tag) Then
                    tmpTB.TextAlign = tbAlignment

                Else
                    If WatchForExceptions Then
                        If Not tmpTB.Tag.ToString.StartsWith("x") Then
                            tmpTB.TextAlign = tbAlignment

                        End If
                    Else
                        tmpTB.TextAlign = tbAlignment
                    End If

                End If
            End If
        Next
    End Sub

How to use the above Subroutine:

This will set the textbox alignment for the current form to center:

SetTextBoxAlignment(Me, HorizontalAlignment.Center)

If you want to set the alignment for most of the textboxes but one or two, place an "x" in the Tag properties of those textboxes you which to exclude. Then use this line to set the alignment for all the textboxes except the ones you "Tagged".

SetTextBoxAlignment(Me, HorizontalAlignment.Center, True)

hi the_carpenter,
i want to thank you for your time to reply my post, i've tried out your code and it works like a charm =p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.