Subscribe

RSS Feed (xml)

Working With DropDownLists in ASP.NET

The ASP.NET Web controls provide a rich object-oriented API to allow you to easily
manipulate them.The following code instantiates a DropDownList and populates it with
four items using several techniques. It also demonstrates how to dynamically set the
selected item.
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
‘ Instantiate the control
ColorDropDownList = New DropDownList()
‘ Add an item using a string
ColorDropDownList.Items.Add(“Blue”)
‘ Add an instance of a ListItem constructed with a string
ColorDropDownList.Items.Add(New ListItem(“Green”))

‘ Add an instance of a ListItem constructed with a text and a value
ColorDropDownList.Items.Add(New ListItem(“Red”, “Red”))
‘ Add a blank item to the top of the list
ColorDropDownList.Items.Insert(0, New ListItem(“”))
‘ Set the selected item
ColorDropDownList.Items(0).Selected = True
‘ Add the control to a PlaceHolder on the page
PlaceHolder1.Controls.Add(ColorDropDownList)
End Sub


There are several ways to set the selected item, just as there are several ways to add items.
You can also set the control’s SelectedIndex to an appropriate value, or find a particular
Item in its Items collection by using the Items collection’s FindByText or FindByValue
methods.These methods return a particular item in the list (if one exists that matches
the criteria specified). Also note that inserting a blank first item is a common technique
performed with data-bound DropDownLists, and that this must be done after the list has
called its DataBind() method.

No comments:

Archives

Variety in the Web World