Just a Day back, we were assigned a Task where in we had a situation, where we load the data in an asp.net form, save that form and open another form, the data from prior form used to get displayed on some of the controls (textbox, Dropdown list). In short loading and saving forms wasn’t clearing the controls.
In order to do so, it would have been very tedious to get each and every control on the page and set the value as null each time the page loads, like
Textbox1.txt=” “;
So what do we do in case we have page with 50 asp.net controls?
Well the following method will take care of that
using System.Web.UI.WebControls;
Public static void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
else if (ctrl is DropDownList)
((DropDownList)ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}and call it like
ClearInputs(Page.Controls);We can also make use of case statement here like
foreach (Control contl in pageControls)
{
string strCntName = (contl.GetType()).Name;
switch (strCntName)
{
case "TextBox":
TextBox tbSource = (TextBox)contl;
tbSource.Text = "";
break;
case "RadioButtonList":
RadioButtonList rblSource = (RadioButtonList)contl;
rblSource.SelectedIndex = -1;
break;
case "HtmlInputText":
HtmlInputText htsource = (HtmlInputText)contl;
htsource.Value = "";
break;
}
ResetFields(contl.Controls);
}
No comments:
Post a Comment