THE BORING WAY
//Clearing all the controls one after the other
private void ClearControls()
{
txtName.Text= string.Empty;
txtAddress.Text = string.Empty;
txtEmail.Text = string.Empty;
txtTelephone.Text = string.Empty;
txtFax.Text = string.Empty;
txtRemark.Text = string.Empty;
}
THE SMART WAY (C#.NET)
//Loop through all the input controls on the page and empty them
public static void ClearControls(Control control)
{
try
{
foreach (Control ctrl in control.Controls)
{
if (ctrl is TextBox)
{
(ctrl as TextBox).Text = string.Empty;
}
else if (ctrl is DropDownList)
{
(ctrl as DropDownList).SelectedIndex = 0;
}
else if (ctrl is CheckBox)
{
(ctrl as CheckBox).Checked = false;
}
ClearControls(ctrl);
}
}
catch (Exception ex)
{
}
}
THE SMART WAY (VB.NET)
'Loop through all the input controls on the page and empty them
Public Shared Sub ClearControls(control As Control)
Try
For Each ctrl As Control In control.Controls
If TypeOf ctrl Is TextBox Then
TryCast(ctrl, TextBox).Text = String.Empty
ElseIf TypeOf ctrl Is DropDownList Then
TryCast(ctrl, DropDownList).SelectedIndex = 0
ElseIf TypeOf ctrl Is CheckBox Then
TryCast(ctrl, CheckBox).Checked = False
End If
ClearControls(ctrl)
Next
Catch ex As Exception
End Try
End Sub
USAGE
//Call the method and pass Page as the parameter ClearControls(Page);
SUMMARY
The method above takes a control as parameter loops through the control looking for text boxes, combo boxes and check box and setting them to their default values. You will notice that the method was called within itself this is called a recursive (to know more about recursive visit this post) this makes sure that if there are container controls like asp panel or content place holders it steps into the controls and clear input controls in the container.
nice read! i like...
ReplyDelete