How To Clear The Values Of All Input Controls On An ASP.NET Web Form Page At A Go

So one of the most boring things you have to do as an asp.net web developer is to have to clear all values on input control after submission of the form . Usually i would have to clear the values of each control one after the other till there was no control to be cleared (trust me this is boring). I then thought there had to be an easier way to achieve this so i got my hands dirty and came up with a way to achieve this. Without further ado see the how in the code snippets below

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.

1 comment :