Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a TextBox in ASP.NET

Tags:

c#

asp.net

I have webpage where there is textbox with some default value. I have to clear that value from the textbox. I have two options:

textbox.text="";

or

textbox.text.remove(0,length);

Which one should I use? Does it make any impact on page performance (there are many textboxes placed on my page)?

like image 789
Hemant Kothiyal Avatar asked Dec 24 '09 10:12

Hemant Kothiyal


4 Answers

The best way to do this is

textbox.text = string.Empty;

Also remember that string type is immutable!

like image 175
this. __curious_geek Avatar answered Nov 19 '22 17:11

this. __curious_geek


It makes no difference - do what is most readable for you and your colleagues.

Many prefer to use string.Empty.

like image 20
Rex M Avatar answered Nov 19 '22 15:11

Rex M


  1. The performance difference between the two options will be too small to measure, most likely.
  2. TextBox.Text = String.Empty; is a lot more readable. It clearly states what you're trying to do: "set the text property of this text box to an empty string".

I recommend you go with the assignment, as it is both faster, and much more clear.

like image 3
John Saunders Avatar answered Nov 19 '22 16:11

John Saunders


Presumably, you mean clear the value with javascript when a user clicks int the box? If so, it won't make any difference to performance.

I use jQuery in most pages, so I just hook up this function to clear default values onClick, using the ClientId of the textbox:

$('#ctl00_TextBox').click(function() { $('#ctl00_TextBox').val('');

If you mean clear it in codebehind use this:

yourTextBox.Text = String.Empty;
like image 1
flesh Avatar answered Nov 19 '22 15:11

flesh