How to: Respond to Button Events in DataList, Repeater, or GridView Items
If your, , or control template includes , , or 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
Include a Button, LinkButton, or ImageButton in a control template.
Set the button's CommandName property to a string that identifies its function, such as "sort" or "copy".
Create a method for the ItemCommand event of the containing control. In the method, do the following:
Check the CommandName property of the event-argument object to see what string was passed.
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, thecontains an ImageButton control that displays a shopping cart. The button sends the command AddToCart. The 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
For an example using the DataList Web server control, see.