How do you clear textboxes on postback

  • Thread starter Thread starter jw56578
  • Start date Start date
J

jw56578

When a page does a post back and there is data in a textbox, that
textbox will get automatically repopulated with that data due to the
posting of the form. Disabling viewstate has no affected on textbox
controls, so how do you make it so that the text box value is cleared
out on postback?
 
You can do this explicitly in the Load event:

if(IsPostBack)
{
TextBoxControl.Text = String.Empty;
}
 
When a page does a post back and there is data in a textbox, that
textbox will get automatically repopulated with that data due to the
posting of the form.

That's correct - that's the whole point of having textboxes (and other
user-interactive) controls on web pages :-)
Disabling viewstate has no affected on textbox controls, so how do you
make it so
that the text box value is cleared out on postback?

Well, the trite answer would be to say that if a webpage contains a textbox
where the user can enter text, but the web app behind it isn't actually
interested in that text, why have it on the page in the first place?

But, clearing its value on postback is easy enough. In the Page_Load event
check whether Page.IsPostBck is true and, if it is, set the TextBox
control's Text property to "".
 
Explicitly clear:

private void ClearTextboxes()
{
textbox1.Text = String.Empty;
}

You can also loop through all of them and clear all. Explicit coding, even
when not necessary, makes the code clearer. In other words, I would clear
them explicitly, even if .NET did it for me. Reasoning: They may find that
they need to switch defaults some day (there is a 2.0 discussion on the
ADO.NET model right now).


---

Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 
Back
Top