How to: Add Items in List Web Server Controls
The information in this topic applies to all list Web server controls: ListBox, DropDownList, CheckBoxList, RadioButtonList, and BulletedList. You can add items to a list Web server control in these ways:
-
Add static items at design time.
-
Add items programmatically at run time.
-
Add items using data binding. For details, see How to: Populate List Web Server Controls from a Data Source. You can add items from a data source to static items you create at design time.
When you add a list item, you specify up to three possible properties of the item, as described in the following table.
| Property | Description |
|---|---|
|
The text displayed in the list. | |
|
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 color and the Value property to the HTML value for that color. | |
|
A Boolean value indicating whether the item is selected. In a CheckBoxList control or a multi-selection ListBox control, more than one item can be selected. In a DropDownList control, a RadioButtonList control, or a 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. |
To add static items at design time
-
Type an
<asp:ListItem> element into the page as a child of the list control. For syntax, see ListBox Web Server Control. -
Set the Text and Value properties of the new list item.
-
Optionally, set the Selected property for one or more items. (Note that certain controls allow only one item to be selected.)
-
Repeat steps 1 through 3 for each item to add.
The following code example shows a ListBox control with three statically defined items.
<asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem Text="Red" Value="#FF0000" Selected="True" /> <asp:ListItem Text="Blue" Value="#0000FF" /> <asp:ListItem Text="Green" Value="#008000" /> </asp:ListBox><br />
To add items programmatically
-
Create a new object of type ListItem and set its Text and Value properties.
-
Call the Add method of the control's Items collection and pass it the new object.
The following code example shows how to add ListItem objects to a ListBox control, but the procedure is identical for all list Web server controls.
Protected Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Add(New ListItem("Carbon", "C")) ListBox1.Items.Add(New ListItem("Oxygen", "O")) End Sub
Protected void Button1_Click (object sender, System.EventArgs e) { ListBox1.Items.Add(new ListItem("Carbon", "C")); ListBox1.Items.Add(new ListItem("Oxygen", "O")); }