Free C# Tutorials

home
Stay at Home and Learn

PadLeft and PadRight

 
Computer Tutorials List

 

 

 

 

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 20 blank space characters to the start of the string. Run your programme and test it out. 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.

 

<-- Insert | Remove and Replace in C# -->

<--Back to the C# .NET Contents Page

View all our Home Study Computer Courses