How can I align strings added as listbox items?

南楼画角 提交于 2019-12-06 15:49:35

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.

Look at this csharp-examples article :

Align String with Spaces.

For official reference, look Composite Formatting

Good luck!

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.

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