Right-justify values in a ListBox in C#

Sometimes you need to align values on the right in a ListBox. One example where you might want to do that is if you are displaying numbers and want to align them at their decimal points.

This example uses the following code to display numbers aligned on the right.

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's RightToLoeft property. This makes the control align the values it displays 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 numbers 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 but their decimal points still line up. 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.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.