How can I align strings added as listbox items?

[亡魂溺海] 提交于 2019-12-10 11:38:33

问题


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?


回答1:


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.




回答2:


Look at this csharp-examples article :

Align String with Spaces.

For official reference, look Composite Formatting

Good luck!




回答3:


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.



来源:https://stackoverflow.com/questions/16379340/how-can-i-align-strings-added-as-listbox-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!