繁体   English   中英

在列表框C#中对齐字符串

[英]Aligning string inside listbox c#

我试图将带有空格的strings写入列表框,并使它们保持对齐。

这是代码:

    List<String> treeNames = new List<String>();
    int counter = 1;

    treeNames.Add("Input                ");
    treeNames.Add("Output               ");
    treeNames.Add("Sequence Type        ");

   foreach (String currentData in treeNames)
   {
         listBox1.Items.Add(currentData + " - " + counter.ToString());
         counter+=1;
   }

这是我希望实现的目标:

Input                 - 1
Output                - 2
Sequence Type         - 3

相反,我得到:

Input           - 1
Output               - 2
Sequence Type                   - 3

有什么想法我该如何调整它们?

您可以使用String.PadRight方法,该方法返回一个新字符串,该字符串通过在字符串之间用空格填充指定的总长度来使字符串中的字符左对齐。

假设您的名称最大长度为20个字符:

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

如果您的名字长度为13,这将添加7个空格字符。 如果名称的长度为9,这将添加11个空格字符。 这样,您名字的所有长度末尾将等于20。

foreach (String currentData in treeNames)
{
     listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("-  " + counter.ToString())));
     counter += 1;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM