Most elegant way to clear all the text fields on asp.net page?

  • Thread starter Thread starter Duk Lee
  • Start date Start date
D

Duk Lee

What is the most elegant way to clear all the text fields on asp.net
page? I just don't think that

txtShortName.Text = ""
txtYearFounded.Text = ""
txtCompanyCode.Text = ""
txtCity.Text = ""
txtOwnership.Text = ""
txtAssetsUnderManagement.Text = ""
txtNumberOfAnalysts.Text = ""
txtTotalStaff.Text = ""
txtCorporateOverview.Text = ""
txtInvestmentProcess.Text = ""
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtSuffix.Text = ""
txtPosition.Text = ""
txtNewSoftMinimum.Text = ""
txtNewHardMinimum.Text = ""

is a very smart way to do it.
 
You could iterate through each control in a page using the Controls
collection and then see if the current control is the type of a textbox.

for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls.GetType() == typeof(TextBox))
((TextBox)this.Controls).Text = string.Empty;

}

You may have to tweak this though to make sure you're getting the correct
child controls. For example, instead of using the page or controls full
control collection you may want to start with the htmlform control for the
page or create a recursive mechanism to ensure you're getting all the
controls in the page as this method will usually only load the top level
controls in the hierarchy.
 
What is the most elegant way to clear all the text fields on asp.net
page? I just don't think that

txtShortName.Text = ""
txtYearFounded.Text = ""
txtCompanyCode.Text = ""
txtCity.Text = ""
txtOwnership.Text = ""
txtAssetsUnderManagement.Text = ""
txtNumberOfAnalysts.Text = ""
txtTotalStaff.Text = ""
txtCorporateOverview.Text = ""
txtInvestmentProcess.Text = ""
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtSuffix.Text = ""
txtPosition.Text = ""
txtNewSoftMinimum.Text = ""
txtNewHardMinimum.Text = ""

is a very smart way to do it.

foreach (Control c in Page.Controls)
{
foreach (Control cc in c.Controls)
{
if (cc is TextBox)
{
((TextBox)cc).Text = String.Empty;
}
}
}
 
Back
Top