Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLeft- or right-align text in VB.NET
DescriptionThis example shows how to left- or right-align text in VB.NET. It uses the String.Format method with alignment fields.
Keywordsalign, align text, format, VB.NET
CategoriesVB.NET, Graphics, Strings
 
The String.Format method formats strings. Enclose parameters in the format string in {braces}. After the parameter number (which starts from 0), you can place a comma and an alignment specifier that gives the number of characters that the parameter should occupy. After that, you can add a colon and a custom formatting string for the parameter.

This program displays three strings right-aligned and then three left-aligned. It then displays the current date in several different formats right- and left-aligned.

 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Dim txt As String = ""

    ' Right-aligned text.
    txt &= "|" & String.Format("{0,20}", "Apple") & "|" & _
        vbCrLf
    txt &= "|" & String.Format("{0,20}", "Banana") & "|" & _
        vbCrLf
    txt &= "|" & String.Format("{0,20}", "Cherry") & "|" & _
        vbCrLf

    ' Left-aligned text.
    txt &= "|" & String.Format("{0,-20}", "Apple") & "|" & _
        vbCrLf
    txt &= "|" & String.Format("{0,-20}", "Banana") & "|" & _
        vbCrLf
    txt &= "|" & String.Format("{0,-20}", "Cherry") & "|" & _
        vbCrLf

    ' Right-aligned dates.
    txt &= "|" & String.Format("{0,20:M-d-yy}", Now) & "|" _
        & vbCrLf
    txt &= "|" & String.Format("{0,20:MM-dd-yy}", Now) & _
        "|" & vbCrLf
    txt &= "|" & String.Format("{0,20:MMM-d-yyyy}", Now) & _
        "|" & vbCrLf
    txt &= "|" & String.Format("{0,20:MMMM-d-yyyy}", Now) & _
        "|" & vbCrLf

    ' Left-aligned dates.
    txt &= "|" & String.Format("{0,-20:M-d-yy}", Now) & "|" _
        & vbCrLf
    txt &= "|" & String.Format("{0,-20:MM-dd-yy}", Now) & _
        "|" & vbCrLf
    txt &= "|" & String.Format("{0,-20:MMM-d-yyyy}", Now) & _
        "|" & vbCrLf
    txt &= "|" & String.Format("{0,-20:MMMM-d-yyyy}", Now) _
        & "|" & vbCrLf

    txtResults.Text = txt
    txtResults.Select(0, 0)
End Sub
 
Note that the String.Format method is relatively time consuming. Usually an object's ToString method will give better performance if you don't need the String.Format method's features.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated