如何对齐添加为列表框项目的字符串?

时间:2013-05-04 21:53:45

标签: c# string listbox

我有一个列表框,我想在其中显示一个字符类的名称和高分列表。我使用ListBox.Items.Add为每个字符添加以下字符串:

public String stringHighscore()
    {
        return name + "\t\t\t" + score.ToString();
    }

问题是,当名称超过一定长度时,分数会被推到右侧。列表框看起来像这样(对不起,我的代表不允许我发布图片):

(Link to the listbox image on tinypic)

我原以为这可能是由于“\ t”,但我不确定。我该如何解决这个问题并正确对齐分数?如果我使用两个列表框,一个用于名称,一个用于分数,会更好吗?

3 个答案:

答案 0 :(得分:1)

您可以使用String.PadRight方法。

  

返回一个新字符串,该字符串左对齐此字符串中的字符   用右边的空格填充它们,达到指定的总长度。

假设您name的长度为20个字符,为最大值

public String stringHighscore()
{
     return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}

如果您的姓名长度为13,则会添加7个空格字符。这样,你的所有名字的长度将等于(20)。

答案 1 :(得分:0)

请看这篇csharp-examples文章:

  

Align String with Spaces.

如需官方参考,请查看Composite Formatting

祝你好运!

答案 2 :(得分:0)

在我看来,您最好使用ListView,而不是尝试自己手动对齐任何内容。使用大麦比使用简单的列表框更难,并且所有配置都可以在IDE中完成(我假设您使用的是VisualStudio,或类似功能强大的IDE)。

假设您有一个名为scoresListView的ListView项。在IDE中,您可以将View属性设置为Details,这将导致列表以给定宽度的列呈现,顶部带有标题(我想您想要“Name”和“Score”)。添加列的代码看起来像这样(为了便于阅读,我假设您在C#文件的顶部有一个using System.Windows.Forms子句):

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)

向列表视图添加项目(名称/分数对)可以简单如下:

string myName = "abcdef"; // sample data
int myScore = 450;
scoresListView.Items.Add(new ListViewItem(new string[] { myName, myScore.ToString() } )); // add a record to the ListView

很抱歉没有太多解释,希望现在或将来有所帮助 - ListView是非常有用的控件。

相关问题