PadLeft and PadRight


The PadLeft and PadRight methods in C# can also be used to insert characters. But these are used to add characters to the beginning and end of your text. As an example, add a new button to your form, and a new text box. For the text box, set the Text property to "Pad Left". Double click your button and enter the following code:

string paddingLeft = textBox5.Text;

paddingLeft = paddingLeft.PadLeft( 20 );

textBox5.Text = paddingLeft;

The PadLeft and PadRight methods can take 1 or two parameters. We're just using 1. This will insert blank space characters to the start of the string. The total number of characters will be 20. So, if you have four characters in the text box, PadLeft(20) will add 16 blank spaces, making a total of 20 characters in the text box after the button is clicked.

Run your programme and test it out. Type the text "Pad Left" in the text box. Your text box should look like this before the button is clicked:

A Text Box before Pad Left

And it will look like this after you click the button:

A Text Box after Pad Left

If you don't want to pad with blank spaces, you can use the second parameter. This is the character you want to pad with:

paddingLeft = paddingLeft.PadLeft(20 , '*');

In the code above, we're telling C# to pad with the asterisk character, instead of the default blank spaces. (Note the use of the single quotes surrounding the * character. C# doesn't seem to like you using double quotes, if the type is char.)

If you change your code to the one above, then click the button on your form, the result will be this:

Padding with the asterisk character

If you want to add characters to the end of the string, use PadRight instead of PadLeft.