Partager via


How to: Add Items in List Web Server Controls

The information in this topic applies to the following Web server controls:

You can add items to a list Web server control in the following three ways:

When you add a list item, you specify up to three possible properties of the item. The following table describes these properties.

Property

Description

Text

Specifies the text displayed in the list.

Value

Specifies a value that is associated with an item but is not displayed. For example, you can set the Text property to the name of chemical element and the Value property to the symbol of the element.

Selected

Indicates 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. In a BulletedList control, this setting has no effect.

To add static items at design time

  1. In Design view, select the list control to which you want to add items.

    In the Properties window, click the ellipsis button (VisualStudioEllipsesButton screenshot) in the Items box.

    The ListItem Collection Editor dialog box appears.

  2. Click Add to add a new item.

  3. Select the new item, and then in the properties grid, enter values for its Text, Value, and Selected properties.

  4. Repeat steps 2 and 3 for each item you want to add, and then click OK.

To add items programmatically

  1. Create a new object of type ListItem and set its Text and Value properties. Typically, you create the new ListItem by calling the Add method.

  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

Tasks

How to: Populate List Web Server Controls from a Data Source