Sunday, July 12, 2009

How do you pad a field with spaces in C# ?

I need a text field to take up 15 spaces whether there's anything in those spaces or not. (To make things align nicely)





What's the correct syntax in C#?





I've been trying to use





textbox.Text = myField.ToString ("#,###,###.##");





but it's not working, because if I concatenate that textbox with another textbox, any spaces that don't contain a number are ignored.

How do you pad a field with spaces in C# ?
You probably want to do something like





string myString = "Hello World!";


textBox.Text = myString.PadLeft(15, ' ');





Alternatively, why mess around with padding when you can just right-align the text box?





textBox.TextAlign = HorizontalAlignment.Right;





This way, you can use the values in the textbox without having to remove and then re-insert the padding. Separate the data from the formatting.


No comments:

Post a Comment