简体   繁体   中英

Aligning string inside listbox c#

I'm trying to write strings with spaces into a listbox, and keep them aligned.

Here is the code:

    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;
   }

Here's what I hope to achieve:

Input                 - 1
Output                - 2
Sequence Type         - 3

Instead, I'm getting:

Input           - 1
Output               - 2
Sequence Type                   - 3

Any ideas how can I align them?

You can use String.PadRight method which returns a new string that left-aligns the characters in the string by padding them with spaces on the right for a specified total length.

Let's say you have 20 character maximum length for a name:

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. If your name's length is 9, this will add 11 space characters. That way all your name's lengths will equal 20 at the end.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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