views:

88

answers:

3

Hi all,

I was wondering if there was a way to format 2 strings in a selectlist and display them as following:

String begins with Item1 and spaces following it until 10 spaces are taken up followed by a Delimiter "|" and string 2

So all Selectlist items binded to a drop down list will be displayed as following

Item 1     |Name1
Item 2     |Name2
Item 55    |Name3
Item 500   |Name4
Item 100000|Name5

Thanks in advance.

+1  A: 

You can use System.String.PadRight()

for(int i = 0; i <= 10; i+= 5)
{
  string ItemString = "Item" + i.ToString().PadRight(10, ' ') + "|" + "Name" + i.ToString();
   SelectList.Items.Add(ItemString);
}

would result in

Item0     |Name0
Item5     |Name5
Item10    |Name10

Of course, you'll want to ensure that you're using a fixed-width font in the drop-down list

David Stratton
Thanks. Which fonts are considered fixed-width?
zSysop
Here are a few: http://en.wikipedia.org/wiki/Samples_of_Monospaced_typefaces
David Stratton
and a few more http://www.cfcl.com/vlb/h/fontmono.html
David Stratton
+1  A: 

You can use string format to build the text for the items:

string itemstring = string.Format("Item {0:0000000000}|Name {0}", itemNumber);

If you are using data binding to build the item, you can put the format expression in the DataTextFormatString to have ASP.NET format the items for you.

Jeff Siver
That's a good alternative. I've used this as well, and it works perfectly.
David Stratton
A: 

best way to format it is:

string itemstring = String.Format("{0,-10}|{1}", item, name);
dice