Title: Use StringFormat to align text in columns in C#
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 the example to experiment with it and to see additional details.
|