Partilhar via


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:

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 color and the Value property to the HTML value for that color.

Selected

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

  1. Type an <asp:ListItem> element into the page as a child of the list control. For syntax, see ListBox Web Server Control.

  2. Set the Text and Value properties of the new list item.

  3. Optionally, set the Selected property for one or more items. (Note that certain controls allow only one item to be selected.)

  4. 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

  1. Create a new object of type ListItem and set its Text and Value properties.

  2. 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"));
    }
    

See Also

Reference

CheckBox and CheckBoxList Web Server Controls Overview
DropDownList Web Server Control Overview
ListBox Web Server Control Overview
RadioButton and RadioButtonList Web Server Controls Overview

Concepts

BulletedList Web Server Control Overview