Reputation: 2213
I am trying to add spaces to end of a string in C#:
Trip_Name1.PadRight(20);
Also tried:
Trip_Name1.PadRight(20,' ');
None of this seems to work. However I can pad the string with any other character. Why?
I should have been more specific, here is full code:
lnk_showmatch_1.Text = u_trip.Trip_Name1.PadRight(20,' ');
Upvotes: 20
Views: 33649
Reputation: 141638
String are immutable, they cannot be changed. PadRight
returns a new instance of the string padded, not change the one it was called from. What you want is this:
Trip_Name1 = Trip_Name1.PadRight(20,' ');
There is a great discussion on this StackOverflow question as to why strings are immutable.
EDIT:
None of this seems to work. However I can pad the string with any other character.
Are you actually re-assigning it like the example above? If that is the case - then without more detail I can only think of the following:
EDIT 2:
I should have been more specific
I'm going to take a wild guess based on your naming conventions that you are dealing with HTML / ASP.NET. In most cases, in HTML - white space is collapsed. For example:
<div><a>Hello World</a></div>
<div><a>Hello World</a></div>
Both of the a
tags will render the same because the white-space is being collapsed. If you are indeed working with HTML - that is likely your reason and why the padding works for all other characters. If you do a view-source of the markup rendered - does it contain the additional white spaces?
If you wanted to keep the whitespaces, try applying a CSS style on your element called white-space
and set it to pre
. For example:
<a style="white-space:pre">hello world </a>
That will cause the white-space to be preserved. Keep in mind that using white space like this has disadvantages. Browsers don't render them identically, etc. I wouldn't use this for layout purposes. Consider using CSS and something like min-width
instead.
Upvotes: 29
Reputation: 47530
Keep in mind, that way won't work for any string manipulation functionality because string is immutable. They just return a new string rather than updating the existing instance.
PadRight returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.
string Trip_Name1 = Trip_Name1.PadRight(20,' ');
EDIT:
Your control seems to be trimming the ending spaces. So, try to set the padding for the control rather than for the text.
Upvotes: 4