【问题标题】:Aligning string inside listbox c#对齐列表框内的字符串c#
【发布时间】:2014-01-19 21:48:51
【问题描述】:

我正在尝试将带有空格的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

有什么想法可以让它们对齐吗?

【问题讨论】:

  • 这是 WPF 吗?还是 WinForms?
  • 您不应该使用等距字体吗?
  • 这个 [thread][1] 可能有助于解决您的问题 [1]:stackoverflow.com/questions/4982807/…
  • 看看可能使用 ListView。

标签: c# string text listbox alignment


【解决方案1】:
foreach (String currentData in treeNames)
{
     listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("-  " + counter.ToString())));
     counter += 1;
}

【讨论】:

    【解决方案2】:

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

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

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

    如果您的姓名长度为 13,这将添加 7 个空格字符。如果您的姓名长度为 9,这将添加 11 个空格字符。这样你名字的所有长度最后都会等于 20。

    【讨论】:

    • 好的,成功了!谢谢。现在,我正在尝试将相同的格式化字符串添加到 TreeView 节点中,但由于某种原因,它们完全对齐,即使使用您提供的解决方案,知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多