Composite Formatting


The String.Format, Console.WriteLine, and TextWriter.WriteLine methods provide a different method for formatting strings. These routines can take a composite formatting string parameter that contains literal characters plus placeholders for values. Other parameters to the methods give the values.

The value placeholders have the following format:

  {index[,alignment][:format_specifier]} 

The index value gives the index numbered from 0 of the parameter that should be inserted in this placeholder’s position.

The optional alignment value tells the minimum number of spaces the item should use and the result is padded with spaces, if necessary. If this value is negative, the result is left-justified. If the value is positive, the result is right-justified.

The format_specifier indicates how the item should be formatted.

For example, consider the following code:

  Dim emp As String = "Crazy Bob" Dim sales As Single = -12345.67 MessageBox.Show(String.Format("{0} {1:earned;lost} {1:c} this year", emp, sales)) 

The first placeholder refers to parameter number 0, which has the value Crazy Bob. The second placeholder refers to parameter number 1 and includes a two-part format specifier that displays earned if the value is positive or zero, and lost of the value is negative. The third placeholder refers to parameter number 1 again, this time formatted as currency.

The following text shows the result:

  Crazy Bob lost ($12,345.67) this year 




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net