blah blah blah is here! blah blah » Close

up0down
link

say I have a string array as:

string[] AllFruits = {"Apples $1.50",
"Oranges $1.80",
"Kiwis $3.10",
"Bananas $1.00};
I add them to the listbox as follows:
listBox1.Items.AddRange(AllFruits);

I want the name of the fruits to be aligned LEFT, and the price to be aligned RIGHT of the listbox.

How do I do that? thanks.

I am referring to a standalone application in C#, not a webapplication. I know in ASP.NET, or using Silverlight, it can add a lots of different functionalities, like in http://www.longhorncorner.com/UploadFile/dbeniwal321/SilverlightListBox01042009231701PM/SilverlightListBox.aspx

last answered 7 months ago

3 answers

up2down
link

Here's an easy way to do this.

You'll first need to set the ListBox font to a fixed width font such as Courier New.

The following code will then left align the fruit and right align the price within a field large enough to accomodate the widest item. If you want to right align to the width of the whole listbox, then I'd simply increase 'maxLen' to the maximum number of fixed width characters it can accomodate:

string[] AllFruits = 
{
"Apples $1.50",
"Oranges $1.80",
"Kiwis $3.10",
"Bananas $1.00"
};
int maxLen = 0;
// work out maximum length of the items
foreach(string fruit in AllFruits)
{
if (fruit.Length > maxLen) maxLen = fruit.Length;
}
// fill out all items to maximum length by inserting spaces before the $ sign
for(int i = 0; i < AllFruits.Length; i++)
{
if (AllFruits[i].Length == maxLen) continue;
int index = AllFruits[i].IndexOf('$');
string extraSpaces = new string(' ', maxLen - AllFruits[i].Length);
AllFruits[i] = AllFruits[i].Insert(index, extraSpaces);
}
listBox1.Items.AddRange(AllFruits);

up0down
link

hi Vulpes,

I understand your logic of adding extra spaces.. I try out the code, but it does not seem to work. the price are not aligned RIGHT as what I want.

Apples $1.50
Oranges $1.80
Kiwis $3.10
Bananas $1.00

vulpes
11603

All I can say is that it worked fine when I tried it myself. Have you remembered to use a fixed width font for the ListBox - if you don't then it will come out a mess because different letters/digits will have different widths.

foamy
1822

Can I just note that the ListBox is not the right control for this behavior. A better choice would be ListView or DataGridView I think.

up0down
link

string[] AllFruits = {
};

How to fetch database (Column values) into this array?

hi Vulpes, could you elaborate where is the settings for fixed width font for the ListBox?

vulpes
11603

In the Properties Box for your ListBox control, select the Font property and choose a fixed width font. I used Courier New 8 pt (actually 8.25 pt) when I tried it myself.

that is wonderful, it works. Thank You very much.

Feedback