Title: Right-justify values in a ListBox in C#
Sometimes you may like to right-justify values in a ListBox. For example, you might want to align numbers so they line up at their decimal points.
This example uses the following code to right-justify lists of numbers.
private void Form1_Load(object sender, EventArgs e)
{
double[] values =
{
111111.111111, 888888.888888,
13.38, 7.75, 50.61, 532.21, 8.29, 111.11, 962.38,
49.27, 4.06, 98.45, 896.13, 7.51, 592.09, 238.29,
};
lstPrices.DataSource = values;
lstRightAligned.RightToLeft = RightToLeft.Yes;
lstRightAligned.DataSource = values;
lstFixedWidth.RightToLeft = RightToLeft.Yes;
lstFixedWidth.DataSource = values;
}
The code sets the DataSource for three ListBox controls to an array of double values. Note that all of the values (except the first two, which I'll explain in a moment) have 2 digits after the decimal point so their decimal points line up.
The key is to set a ListBox control's RightToLoeft property. This makes the control align its values on their right edge instead of on their left edge.
Note that some fonts, even some that are not fixed-width fonts, still use fixed widths for digits so right-justified values with the same number of digits after the decimal point still line up nicely. In the middle ListBox, which uses the default font MS Sans Serif, the first two entries display 6 digits after the decimal point and their decimal points still line up even though the digit 1 is skinnier than 8.
In the ListBox on the right, which uses the Arial font, the 1s are thinner than the 8s so the decimal points of the first two entries don't line up. The other decimal points in that ListBox don't line up perfectly either, but it's hard to tell because there are only 2 digits after the decimal point so it's very close.
Download the example to experiment with it and to see additional details.
|