0

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?

4
  • Is this WPF? Or WinForms? Commented Jan 2, 2014 at 12:35
  • 4
    Shouldn't you be using a mono-spaced font? Commented Jan 2, 2014 at 12:36
  • this [thread][1] may help resolve your issue [1]: stackoverflow.com/questions/4982807/… Commented Jan 2, 2014 at 12:37
  • 1
    Look at maybe using ListView. Commented Jan 2, 2014 at 12:38

2 Answers 2

0
foreach (String currentData in treeNames)
{
     listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("-  " + counter.ToString())));
     counter += 1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Ok, it worked! Thanks. Now, I'm trying to add the same formatted string into a TreeView node, but for some reason they are completely aligned, even with the solution you presented, any idea why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.