Align numeric values in ComboBox and ListBox controls in C#

[align numeric values]

The example Sort partly numeric items in a ComboBox or ListBox in C# displays a list of values that begin with numbers. Unfortunately the text doesn’t line up nicely in the result.

This example solves that problem by using a fixed-width font and by padding the numeric parts of the values to the same width. That lets it align numeric values relatively easily.

One problem when trying to align text values is that many fonts use different widths for different letters. For example, in your browser this text probably uses a narrow i character and a wide W character. Compare the widths of the following strings, which contain the same number of characters:

iiiiiiiiii

WWWWWWWWWW

The space character is particularly narrow in many fonts so just trying to blank-pad numeric values as in [ 1] and [123456] gives them different widths (yes, they both contain 6 characters) so they don’t line up nicely.

This example’s form uses the fixed-width font Courier New. That font is available on every Windows computer so you can use it if you need a fixed-width font. It’s the font used by the Visual Studio text editor (open the Tools menu, select Options, expand the Environment page, and select Fonts and Colors.)

The only other interesting technique used by this example is in the following code.

// Left pad the numeric part of the values to 3 characters.
var pad_query =
    from string value in values
    orderby int.Parse(value.Split(' ')[0])
    select value.Split(' ')[0].PadLeft(3) +
        value.Substring(value.IndexOf(' '));

// Display the result.
string[] results = pad_query.ToArray();
cboBooks.DataSource = results;
lstBooks.DataSource = results;

This code is similar to the LINQ code used in the previous example except it pads the value’s numeric part so it is 3 characters wide. The select statement splits the string value at its spaces, takes the first entry (the numeric part), and calls its PadLeft method (which is provided by all strings) to make that part of the result 3 characters wide with the extra spaces added on the left. The select statement then adds the rest of the string value to produce the final result.

Using a fixed-width font can be a useful technique for producing quick report-like output where columns must align. It doesn’t always look as nice as other fonts such as Times New Roman, Arial, or Segoe, but it’s much easier to make things line up nicely.


Download Example   Follow me on Twitter   RSS feed   Donate








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

Leave a Reply

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