Show multiple columns in a dropdown with proper alignment

The problem : We have an ID column and a Name column in our database. We want to show both in a dropdown but if you concatenate both, you will notice that the alignment goes out of whack.

eg. 1
1 – Item one
2 – Item two
20 – Item twenty
100 -Item hundred
3 – Item 3

See what I mean. The alignment is completely out of whack. What we want to achieve here should kinda look like below.

eg. 2
1   – Item one
2   – Item two
20  – Item twenty
100 – Item hundred
3   – Item 3

So we have multiple problems here. One is that in most of the fonts every character takes up a different amount of space. eg. A will take more space on the screen than lower caps a. The other problem, is how to write our stored procedure in a way that it pads the extra spaces as in e.g 2 above

The Solution :
1. The solution to the problem with characters taking different screen space is very simple. All we need to do is use something called a Monospace font. Create a style like below :
/* Monospace font – same width for all characters */
.monospace{ FONT-SIZE: 8pt; font-family: monospace;}

If you are using ASP.Net just set your dropdown’s cssClass=”monospace”. If your are using plain html, just set the class=”monospace”

2. That takes care of problem #1. Now, let us kill the 2nd bird.
In your stored proc, do something like this :

LEFT(LEFT(Name,25) + REPLICATE(‘.’,25),26) + Cast([Id] as varchar(3)) As IDName,

That is it. The IDName column will give you the perfectly aligned characters and Dots will be stuffed in between the name and id so that they align up nicely. The output is something like this (for someone reason wordperss is messing up the formatting..but I hope you get what I mean):

Item number t….2
Item# 20 ……..20
Item # hundred…100

If you want the output, flipped around. i.e IDs showing first and Names showing later, change your select to this :

LEFT(Cast([Id] as varchar(3)) + REPLICATE(‘.’,4),5) + Left([Name],25) As IDName,

This will give you output like this :
2……Item number 2
30…..Item 30
299….Item 299

Hope you find this useful. Happy coding!!!


One thought on “Show multiple columns in a dropdown with proper alignment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s