Search code examples
c#labelalignment

How to align a part of a label to the right of a group box? WinForm C#


I am developing an application that displays lines of data pulled from an SQL server. When trying to display the information, I want to put the description of the data and the data itself in the same label, but have the data portion right aligned to the group box the label is in. That way the data is easily readable at a glance.

An example of how this would look is:

Fav Food:       Pizza
Fav Color:      Blue
Fav Program:    Visual Studio

This is what I want the labels to look like inside the groupbox, with the longest data a few pixels from the right of the groupbox.

xFavFoodLabel.Text = "Fav Food: ".PadRight(50 - "Fav Food: ".Length) + favfood;
xFavColorLabel.Text = "Fav Color: ".PadRight(50 - "Fav Color: ".Length) + favcolor;
xFavProgramLabel.Text = "Fav Program: ".PadRight(50 - "Fav Program: ".Length) + favprogram;

I wanted this to display the text like the example above, but instead the text was staggered and did not look right. Any ideas?


Solution

  • The font you choose matters.

    You are assuming each character takes the same amount of horizontal space. While it is true for a Monospaced font like Courier, it is not for a proportional font. You can set the font as Courier to see if it makes any difference.

    For tabular layout, it is more easier to use TableLayoutPanel to arrange the labels.

    Define 2 columns, and put the description label and the value label into separate column. You can then even have different alignment for each label, like right-aligning description labels and left-aligning value labels.