Saturday, April 25, 2009

Recursive function in Asp.Net

An important programming technique is the Recursion.
Recursive is a procedure or subroutines that contains a statement that calls itself.

In this simple example I use a recursive function to clean all TextBox even those within a container (ascx control)


Private Function CleanAll(ByVal container As Control) As ArrayList

Dim txt As TextBox
For Each c As Control In container.Controls
If c.GetType.Name = "TextBox" Then
txt = c
If txt.Text <> "" Then
txt.Text = ""
allControlls.Add(c)
End If
Else
CleanAll(c) ' invokes recursively the method
'to add more controls in the control children
End If
Next
Return allControlls

End Function

There are two ascx controls nested one inside the other.
The same thing works with panels and other asp.net containers.
If you want, you can download this example here (visual basic) or here (c#).

For more info try here and here.

That's all !

1 Comments:

Anonymous said...

With LINQ this could have been a 1-liner :-)

2012 | aspnet code by Michele | don't try this at home
Mirko Iodice Notageek
Vladimir Carrer Carrer web log