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 !

Wednesday, April 1, 2009

Add Item to DropDownList

Hi!

In this post I'll explain how to add a custom-item in a DropDownList using ListItem object.

As written in MSDN:

"ListItem represents a data item in a data-bound list control"
"A ListItem control represents an individual data item within a data-bound list control"

First of all, we have to connect a Database Table with a DropDownList. (you can see how populate a DropDownList here)

Protected Sub GetContact()

Dim obj As cl_Person = Nothing
obj = New cl_Person(System.Configuration.ConfigurationManager.AppSettings("APPConnectionString"))

Me.ddlPerson.DataSource = obj.GetContact()
Me.ddlPerson.DataValueField = "ContactID"
Me.ddlPerson.DataTextField = "FullName"
Me.ddlPerson.DataBind()

End Sub

Then in the DataBound event of the DropDownList, write this:

Protected Sub ddlPerson_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPerson.DataBound

Dim myItem As New ListItem
myItem.Text = "Choose One !!!"
myItem.Value = 0
myItem.Selected = True
Me.ddlPerson.Items.Add(myItem)

End Sub

As you can see, "Choose One !!!" rapresents our custom-item.



If you want, you can download this example here.
You can download and install AdventureWorksDB.msi database here.

Please remember to change in the web.config file, the two values "Data Source=pc01;" with
your sqlserver instance name. (probably "computername" with Sql2005/2008, but if you are using SqlExpress edition your instance name is "computername\SQLExpress")

That's all !

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