Formatting Strings in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes how to format the strings in VB.NET

The String.Format method is taking a composite formatting string parameter that contains literal characters plus placeholders for values. Other parameters in the the method gives the values.

The value placeholder has the next format:
{ index [, alignment ][: format_string ] }

The index value gives the index numbered (zero based) of the parameter that should be inserted in that placeholder's position.

    Dim project As String = "World"
    Dim result As String = String.Format("Hello {0}!", project)
    MessageBox.Show(result) ' = Hello World!               


The alignment value is optional and it defines a minimum number of spaces the item should use.
If alignment is negative, the result is left-justified and if it's positive, the result is right-justified.

    Dim amount As Decimal = 500
    Dim result As String = String.Format("{0, -20} {1, -3} dollars", _
     "Thanks for paying me ", amount)
    Console.WriteLine(result) ' = Thanks for paying me 500 dollars             



The format_string is also optional and indicates how the item will be formatted:

    Dim amount As Decimal = 500
    Dim result As String = String.Format("{0, -20} {1, 10:c}", _
     "Thanks for paying me ", amount)
    Console.WriteLine(result) ' = Thanks for paying me      $500.00


Please notice that braces { } are required

Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.