Controls You Can Use on Web Forms ASP.NET Standard Controls ListBox Control
NOTE: The information in this topic applies to all list Web server controls: ListBox, DropDownList, RadioButtonList, and CheckBoxList.
You can add items to a list Web server control in these ways:
When you add a list item, you specify up to three possible properties of the item, as described in the following table.
Property |
Description |
Text |
The text displayed in the list. |
Value |
The value associated with an item. Setting this property allows you to associate a value with a specific item without displaying it. For example, you can set the Text property to the name of a U.S. state and the Value property to its postal abbreviation. |
Selected |
A Boolean value indicating whether the item is selected. In a CheckBoxList control and in a multi-selection ListBox control, more than one item can be selected. In a DropDownList control, RadioButtonList control, and single-selection ListBox control, only one item can be selected at a time. If you set more than one selected item in these controls, the browser determines which item is rendered as selected. |
- Declare the type of list item element on the page using syntax appropriate to the control.
- Specify a caption by setting the list item’s Text property.
- Optionally set the Value property associated with the item.
- Optionally set which of the list items are initially chosen by setting the control’s Selected property.
For more information, see Adding Web Server Controls to a Web Forms Page.
- Call the Add method of the control’s Items collection and pass it a new object of type ListItem, specifying its Text and Value properties.
The following example shows how to add a ListItem object to a ListBox control using the value supplied from a TextBox control. This procedure is the same for all the Web server controls that derive from the ListControl class.
void addToList ( object src, EventArgs e ) {
colorSelect.Items.Add ( txtColor.Value );
}
Sub addToList ( ByVal source As Object, ByVal e As EventArgs )
colorSelect.Items.Add ( New ListItem ( txtColor.Value ) )
End Sub |
|
C# |
VB |
The following examples demonstrate different ways of how you can programmatically add new items to a list control.
Populating a List Control from a Database Determining the Selection in a List Control