Menu

Want to work with us? We're on the lookout for a talented Digital Project Manager.

We're hiring

Clear Controls On Asp.Net Page

Web Bureau


11 December 2010 by Web Bureau

Simple solution for clearing the controls on an asp.net page, the code can be reused for multiple pages eliminating the need the write multiple routines to clear controls on a page.

Public Shared Sub Clear_Controls(ByVal parent As Control)

        For Each c As Control In parent.Controls

            If c.GetType() Is GetType(TextBox) Then
                Dim tb As TextBox = DirectCast(c, TextBox)
                If tb IsNot Nothing Then
                    tb.Text = String.Empty
                End If
            End If
            If c.GetType() Is GetType(DropDownList) Then
                Dim ddl As DropDownList = DirectCast(c, DropDownList)
                If ddl IsNot Nothing Then
                    ddl.ClearSelection()
                End If
            End If
            If c.GetType() Is GetType(CheckBox) Then
                Dim cbx As CheckBox = DirectCast(c, CheckBox)
                If cbx IsNot Nothing Then
                    cbx.Checked = False
                End If
            End If
            If c.GetType Is GetType(CheckBoxList) Then
                Dim cbl As CheckBoxList = DirectCast(c, CheckBoxList)
                If cbl IsNot Nothing Then
                    cbl.ClearSelection()
                End If
            End If
            If c.GetType Is GetType(ListBox) Then
                Dim lbx As ListBox = DirectCast(c, ListBox)
                If lbx IsNot Nothing Then
                    lbx.ClearSelection()
                End If
            End If

            If c.HasControls = True Then
                Clear_Controls(c)
            End If

        Next

    End Sub

You can also add in more controls if they are not already included in the routine.

Grow your businessStart a project with us today.