Reputation: 35
I have a listbox where I want to display a list of names and highscores from a character class. I use ListBox.Items.Add
to add the following string for each character:
public String stringHighscore()
{
return name + "\t\t\t" + score.ToString();
}
The problem is that when the name exceeds a certain length, the score gets pushed to the right. The listbox looks like this (sorry, my rep doesn't allow me to post images yet):
(Link to the listbox image on tinypic)
I have thought this may be due to the "\t" but I am not sure. How can I solve this and properly align the scores? Would it be better if I used two listboxes, one for names and one for scores?
Upvotes: 1
Views: 11445
Reputation: 699
Seems to me like you would be best off using a ListView rather than trying to manually align anything yourself. Usage is barley harder than working with simple list boxes, and all the configuration can be done in the IDE (I'm assuming you are using VisualStudio, or a similarly powerful IDE).
Say you have a ListView item called scoresListView
. From the IDE you can set the View property to Details, which will cause the list to be rendered in columns of a given width with a heading at the top (I figure you would want "Name" and "Score"). The code to add a column looks something like this (I assume you have a using System.Windows.Forms
clause at the top of your C# file for the sake of readability):
scoresListView.Columns.Add("Name", 200); // add the Names column of width 200 pixels
scoresListView.Columns.Add("Score", 200, HorizontalAlignment.Right); // add the Score column of width 200 pixels (Right Aligned for the sake of demonstration)
Adding items (a name/score pair) to the list view can be as simple as:
string myName = "abcdef"; // sample data
int myScore = 450;
scoresListView.Items.Add(new ListViewItem(new string[] { myName, myScore.ToString() } )); // add a record to the ListView
Sorry there isn't all that much explanation, hope this helps now or in the future - the ListView is a very useful control.
Upvotes: 0
Reputation: 98740
You can use String.PadRight
method.
Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.
Let's say you have 20 characters length for name
as maximum
public String stringHighscore()
{
return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}
If your name's length is 13
, this will add 7
space characters. And that way, your all name's length will equal (20
) at the end.
Upvotes: 1
Reputation: 2612
Look at this csharp-examples article :
For official reference, look Composite Formatting
Good luck!
Upvotes: 0