Sunday, April 12, 2009

Clear form values

The following code will clear values entered in the form, currently only works with drop down list and textbox, you can expand it to cater for more controls.

Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click

ClearValues(Me.FindControl("MyControlID"))

End Sub

Private Sub ClearValues(ByVal container As Control)

For Each ctl As Control In container.Controls

Dim textBox As TextBox = TryCast(ctl, TextBox)

If textBox IsNot Nothing Then

If textBox.Text.Trim().Length <> 0 Then

textBox.Text = ""

End If

End If

If TypeOf ctl Is UI.WebControls.DropDownList Then

Dim ddl As UI.WebControls.DropDownList = DirectCast(ctl, UI.WebControls.DropDownList)

Dim li As ListItem = ddl.Items.FindByText("(none)")

If li IsNot Nothing Then

ddl.SelectedValue = li.Value

End If

li = ddl.Items.FindByText("Select")

If li IsNot Nothing Then

ddl.SelectedValue = li.Value

End If

End If

If ctl.Controls.Count > 0 Then

ClearValues(ctl)

End If

Next

End Sub

blog comments powered by Disqus