Powered by Blogger.

Formatting Strings in Visual Basic .NET

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.



1
2
3
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.

1
2
3
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:

1
2
3
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