|
-
Oct 29th, 2008, 10:28 PM
#1
Formatting Fixed-width Text Output
VB 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:
CSharp Code:
StringBuilder builder = new StringBuilder(); string format = "{0,-4}{1,-10}{2,-12:d}{3,8}"; builder.AppendFormat(format, "ID", "Name", "DOB", "Children"); builder.AppendLine(); builder.AppendFormat(format, 1, "Peter", new DateTime(1969, 6, 19), 2); builder.AppendLine(); builder.AppendFormat(format, 2, "Paul", new DateTime(1974, 4, 23), 4); builder.AppendLine(); builder.AppendFormat(format, 3, "Mary", new DateTime(1980, 12, 4), 1); builder.AppendLine(); this.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 22nd, 2013 at 05:46 PM.
Reason: Fixed DateTime constructor parameter order.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|