C# 在listbox c中对齐字符串
我试图将带有空格的字符串写入列表框,并保持它们对齐 代码如下:C# 在listbox c中对齐字符串,c#,string,text,listbox,alignment,C#,String,Text,Listbox,Alignment,我试图将带有空格的字符串写入列表框,并保持它们对齐 代码如下: List<String> treeNames = new List<String>(); int counter = 1; treeNames.Add("Input "); treeNames.Add("Output "); treeNames.Add("Sequence Type ");
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
您知道如何对齐它们吗?您可以使用String.padrright方法,该方法返回一个新字符串,该字符串通过在右侧填充指定总长度的空格来左对齐字符串中的字符 假设名称的最大长度为20个字符:
public String stringHighscore()
{
return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}
如果您的姓名长度为13,这将添加7个空格字符。如果您的姓名长度为9,则将添加11个空格字符。这样,您的名字的所有长度都将在结尾处等于20。这是WPF吗?或者WinForms?您不应该使用单间距字体吗?此[thread][1]可能有助于解决您的问题[1]:看看是否可以使用ListView。好的,它成功了!谢谢现在,我正在尝试将相同的格式化字符串添加到TreeView节点中,但出于某种原因,它们完全对齐,即使与您介绍的解决方案一致,知道为什么吗?
foreach (String currentData in treeNames)
{
listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("- " + counter.ToString())));
counter += 1;
}
foreach (String currentData in treeNames)
{
listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("- " + counter.ToString())));
counter += 1;
}