Results 1 to 2 of 2

Thread: Formatting Fixed-width Text Output

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Formatting Fixed-width Text Output

    C# version here.

    Lots of people ask how to display text formatted in columns. It's generally a bad idea to display a solid block of text formatted that way. More often you should use a grid control or a ListView, but if you really want to display tabular data in a TextBox, or perhaps in a file with fixed-width columns, then you'd do it much like this:
    vb.net Code:
    1. Dim builder As New System.Text.StringBuilder
    2. Dim format As String = "{0,-4}{1,-10}{2,-12:d}{3,8}"
    3.  
    4. builder.AppendFormat(format, "ID", "Name", "DOB", "Children")
    5. builder.AppendLine()
    6. builder.AppendFormat(format, 1, "Peter", #6/19/1969#, 2)
    7. builder.AppendLine()
    8. builder.AppendFormat(format, 2, "Paul", #4/23/1974#, 4)
    9. builder.AppendLine()
    10. builder.AppendFormat(format, 3, "Mary", #12/4/1980#, 1)
    11. builder.AppendLine()
    12.  
    13. Me.TextBox1.Text = builder.ToString()
    The secret there is the format string. You can use a format string with a StringBuilder.AppendFormat, Console.WriteLine, String.Format, StreamWriter.WriteLine and other places, so your output options are many. Let's take a closer look at that format string.

    It includes 4 format specifiers, so it will accept 4 values to format. You'll see that each call to AppendFormat passes the format string followed by 4 values. Funny, that.

    The first format specifier ({0,-4}) takes the first value ({0,-4}) and pads it out with whitespace to 4 characters ({0,-4}), left-aligning the string ({0,-4}).

    The second format specifier take the second value, pads it out to 10 characters and left-aligns it.

    The third format specifier ({2,-12:d}) takes the third value, pads it out to 12 characters, left-aligns it and displays it in the short date format ({2,-12:d}).

    The fourth format specifier takes fourth value and pads it out to 8 characters, but this time the field width is greater than zero so it is right-aligned.

    Note that to actually view the output in columns you must use a fixed-width font. Notepad will do that by default but if, if you're displaying the data in a TextBox, you must set the Font to Courier New or some other appropriate value.
    Last edited by jmcilhinney; Oct 29th, 2008 at 10:29 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width