How to: Respond to Button Events in Data-Bound Controls
If you are using a data-bound control with templates (such as a DataList or FormView control), and the templates include Button, LinkButton, or ImageButton Web server controls, the buttons can forward their Click events to the containing control. This allows you to include buttons for custom functionality not already defined for the data bound control (such as edit, delete, update, and cancel).
To respond to button events in data-bound controls
Add 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 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, the ItemTemplate contains 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 appropriate logic.
Private Sub DataList1_ItemCommand(ByVal source As Object, _ ByVal e As DataListCommandEventArgs) _ Handles DataList1.ItemCommand 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
private 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. } }
See Also
Tasks
How to: Create Event Handlers in ASP.NET Web Pages