Reputation: 13
i want to add a space ( ) in text box until the maximum length reached (1000)
and i want to write text in the textbox concat the space so the text is first and after the text finished the space start until max length of textbox reached for example.
like below :
textbox1.text = "mytext" + " ";
but i want the space just to fill the textbox until max length (1000) reached.
and the other thing i want is if the text in the textbox is bigger than the max length then remove the excess (the text after 1000)
please help
Upvotes: 0
Views: 876
Reputation: 48425
First check if the length is greater than the maximum permitted, if it is then use Substring
to cut it down to size. If the length is less than max, then you can use PadRight
to pad the text...
string text = textbox1.Text;//get the text to manipulate
int max = 1000;
if(text.Length > max)//If the current text length is greater than max
text = text.Substring(0, max);//trim the text to the maximum allowed
else
text = text.PadRight(max, ' ');//pad extra spaces up until the correct length
//text will now be the same length as max (with spaces if required)
textbox1.Text = text;//set the new text value back to the TextBox
NOTE: Because you have asked about trimming the text to the maximum length, then I have assumed you have not used the MaxLength
property of the TextBox
- as this would already prevent adding more than the limit, I would recommend using that instead then you don't have to worry about trimming yourself, you could then just do:
textbox1.Text = textbox1.Text.PadRight(textbox1.MaxLength, ' ');
Upvotes: 1
Reputation: 101
I think that's all you wanted right?
public String writeMax(String myText, int maxLenght)
{
int count = myText.Length;
String temp = "";
if(count >= maxLength)
{
temp = myText.substring(0, maxLength);
}
else
{
for(int i = 0; i < maxLength - count; i++)
{
temp += " ";
}
temp = myText + temp;
}
return temp;
}
Upvotes: 0
Reputation: 10191
You can use the string.PadRight() method.
textbox1.Text = textbox1.Text.PadRight(textbox1.MaxLength, ' ');
Upvotes: 6