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
 
 
 
 
 
TitleUse a composite format specifier in VB .NET
DescriptionThis example shows how to use a composite format specifier in VB .NET.
Keywordsformat, format specifier, string, VB.NET
CategoriesVB.NET, Strings
 
The String.Format method takes as parameters a format string followed by any number of parameters. The format string can contain tokens that represent the parameters that follow. The tokens have the form:

    {num,size:fmt}

Where:

  • num: The index of the parameter to use, indexed starting with 0.
  • size: (Optional) The minimum number of spaces that the result should occupy. If this is positive, the value is right-aligned. If it is negative, it is left-aligned.
  • fmt: The field's format string. Check the online help for specific values.
Other text in the format string is displayed literally. For example, the following code displays parameter 0 (the first one after the format string). It is right-aligned within 10 characters. The E indicates scientific notation.

    Debug.WriteLine("Value: {0,10:E}", the_value)

The following code displays the second parameter. The format string has three parts separated by semi-colons. They give the format that should be used if hte value is positive, negative, or zero.

    Debug.WriteLine("Value: {1:Plus;Minus;Zero}", value0, value1)

This example program lets you enter values and enter or pick format strings to see the results. When you change the value or format string, the ShowValue routine displays the result. The txtValue TextBox conntains the values separated by commas. The subroutine separates these values, converts them into Doubles, and passes them and the format string to the String.Format method.

 
Private Sub ShowValue()
    Try
        ' Get the value.
        Dim strings() As String = Split$(txtValue.Text, ",")
        Dim values(strings.GetUpperBound(0)) As Object
        For i As Integer = 0 To strings.GetUpperBound(0)
            values(i) = Double.Parse(strings(i))
        Next i
        txtResult.Text = String.Format(cboFormat.Text, _
            values)
    Catch ex As Exception
        txtResult.Text = ""
    End Try
End Sub
 
Experiment with it and consult the online help about format strings to learn more.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated