Introduction
When we are making a registration form or a form having many textbox
es, i.e.,[10,20-50 textbox
es] in a single page and we have to clear all the textbox
es at once after submission, what we do is write dozens of lines for every textbox
out there in form or page.
If you have one or two textbox
es, then it is ok.
Just use textbox-id.Text="";
and it will clear the textbox
text.
But when we have many textbox
es in a single page of form, then we have to use something better to do that and here this code comes in.
So just read, understand and apply it.
Background
You need a little bit of information about how to create a control in ASP.NET from code-behind.
Using the Code
Here, I have taken a div
in which I have placed my textbox
and other controls in it.
<div id="feedback" runat="server">
<h3>Feedback</h3>
Name:
<asp:TextBox ID="name" runat="server" ></asp:TextBox>
Email:
<asp:TextBox ID="email" runat="server" ></asp:TextBox>
Tell us:
<asp:TextBox ID="text" runat="server"
CssClass="feedbacktextbox" TextMode="MultiLine" >
</asp:TextBox>
<asp:Button ID="b1" CssClass="feedbackbtn"
runat="server" Text="Submit" OnClick="b1_Click" />
</div>
So, now on code-behind, when button is clicked, it runs the code in which a foreach
-loop loops through our division and finds the TextBox
control, wherein code below b
is Control which will loop through our division.
c
is a textbox
control we declared.
And what will happen after that is below:
protected void b1_Click(object sender, EventArgs e)
{
foreach ( Control b in feedback.Controls )
{
TextBox c;
if (b is TextBox)
{
c = b as TextBox;
if (c != null)
{
c.Text = String.Empty;
c.Text="";
}
}
}
}
Points of Interest
Using this will save us from writing dozens of lines to clear TextBox
text.
So, guys, use it or leave it. It's your choice. :)