共用方式為


How to: Respond to Button Events in DataList or Repeater Items

If a DataList or Repeater control template includes Button, LinkButton, or ImageButton Web server controls, these buttons can send their Click events to the containing DataList or Repeater control. This enables you to include buttons for functions that are not already defined for the DataList control (edit, delete, update, and cancel) and to define functionality for the Repeater control.

To respond to button events in DataList and Repeater controls

  1. Include a Button, LinkButton, or ImageButton in a control template.

  2. Set the button's CommandName property to a string that identifies its function, such as "sort" or "copy".

  3. Create a method for the ItemCommand event of the containing control. In the method, do the following:

    1. Check the CommandName property of the event-argument object to see what string was passed.

    2. Perform the appropriate logic for the button that the user clicked.

    The following example shows how you can respond to a button click in a DataList control. In the example, the ItemTemplate contains an ImageButton control that displays a shopping cart. The button sends the command AddToCart. The ItemCommand event handler determines which button was clicked, and — if it was the shopping cart button — performs the appropriate logic.

    Protected Sub DataList1_ItemCommand(ByVal source As Object, _
            ByVal e As DataListCommandEventArgs)
        If e.CommandName = "AddToCart" Then
            ' Add code here to add the item to the shopping cart.
            ' Use the value of e.Item.ItemIndex to retrieve the data 
            ' item in the control.
        End If
    End Sub
    
    protected void DataList1_ItemCommand(object source, 
        DataListCommandEventArgs e)
    {
       if (e.CommandName == "AddToCart")
       {      
          // Add code here to add the item to the shopping cart.
          // Use the value of e.Item.ItemIndex to retrieve the data 
          // item in the control.
       }
    }
    

    For an example using the DataList Web server control, see How to: Allow Users to Select Items in DataList Web Server Controls.

See Also

Tasks

How to: Allow Users to Edit Items in DataList Web Server Controls

How to: Allow Users to Delete Items in DataList Web Server Controls

How to: Respond to Button Events in a GridView Control

Reference

DataList Web Server Control Overview

Repeater Web Server Control Overview