Wednesday, April 1, 2009

Add Item to DropDownList


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"

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

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