Partilhar via


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

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

To respond to button events in DataList, Repeater, and GridView 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 find the data row
            ' in the data source.
        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 find the data row
          // in the data source.
       }
    }
    

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

Reference

DataList Web Server Control Overview