Use StringFormat to align text in columns in C#

[StringFormat]

My previous post Use tabs and StringFormat to align text in C# showed how to use a StringFormat object to draw tab-delimited text in columns. Unfortunately, that method doesn’t give you control over how the values in each column are aligned.

This example uses the following code to draw text in columns that can each have a different alignment.

// Draw some text aligned in columns.
private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

    string headings = "Title\tPrice\t# Pages\tYear";
    string[] lines =
    {
        "WPF 3d\t$34.95\t430\t2018",
        "The C# Helper Top 100\t$24.95\t380\t2017",
        "Interview Puzzles Dissected\t$15.95\t300\t2016",
        "C# 24-Hour Trainer, Second Edition\t$45.00\t600\t2015",
        "Beginning Software Engineering\t$45.00\t480\t2015",
        "Essential Algorithms\t$60.00\t624\t2013",
        "Beginning Database Design Solutions\t$44.99\t552\t2008",
        "Powers of Two\t$2.04\t8\t16",
    };

    // Prepare a StringFormat to use the tabs.
    using (StringFormat string_format = new StringFormat())
    {
        // Define the columns' X coordinates.
        float[] xpos = { 10, 500, 575, 650 };

        // Define the column alignments.
        StringAlignment[] alignments =
        {
            StringAlignment.Near,
            StringAlignment.Far,
            StringAlignment.Far,
            StringAlignment.Far,
        };

        // Draw the headings.
        float margin = 10;
        float y = 10;
        using (Font font = new Font("Times New Roman",
            13, FontStyle.Bold))
        {
            string[] strings = headings.Split('\t');
            for (int i = 0; i < strings.Length; i++)
            {
                string_format.Alignment = alignments[i];
                e.Graphics.DrawString(strings[i], font,
                    Brushes.Blue, xpos[i], y, string_format);
            }
        }

        // Draw a horizontal line.
        y += 1.4f * Font.Height;
        float width = xpos[xpos.Length - 1] + 5;
        e.Graphics.DrawLine(Pens.Blue, margin, y, width, y);
        y += 5;

        // Draw the book entries.
        using (Font font = new Font("Times New Roman", 11))
        {
            foreach (string line in lines)
            {
                string[] strings = line.Split('\t');
                for (int i = 0; i < strings.Length; i++)
                {
                    string_format.Alignment = alignments[i];
                    e.Graphics.DrawString(strings[i], font,
                        Brushes.Black, xpos[i], y, string_format);
                }
                y += 1.2f * this.Font.Height;
            }
        }
    }
}

The code first defines the heading labels and the tab-delimited data. It then defines an array of X coordinates and an array of column alignments for the columns.

The code then loops through the column headings. For each heading, the program sets the StringFormat object’s Alignment property to properly align the column. The value Near means the text is drawn to the right of the X coordinate used in DrawString. The value Far means the text is drawn to the left of the X coordinate (so the column is aligned on the right).

After it has drawn the column headers, the code draws a horizontal line below them. It then loops through the tab-delimited data and repeats the previous steps to draw each column’s data in a line of text.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in fonts, graphics, strings and tagged , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Use StringFormat to align text in columns in C#

  1. Piotr Pikielny says:

    Hello,
    Where did you get the values of “float[] xpos = { 10, 500, 575, 650 }; ” from?
    How to calculate these values?

    Regards,
    Piotr

    • RodStephens says:

      I just picked those values through trial and error until I found something that looked good. Be sure to allow room for the scroll bars on the right edge of the control in case the lines won’t all fit and the control displays the scroll bars.

      If you want to calculate this, you can use the Graphics object’s MeasureString method to see how big a string will be when drawn. Allow a bit of extra room for space between the columns. Also add a little extra because some fonts adjust character spacing so MeasureString isn’t always exact.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.