If your DataList control templates include Button, LinkButton, or ImageButton Web controls, then these buttons can bubble their click events to the container control — that is, to the DataList control. This allows you to include buttons for functions not already defined for the DataList control (edit, delete, update, and cancel) and define your own functionality for the list.
Note Only controls that support an OnCommand event can bubble their events to the DataList control. These include the ones listed above.
To respond to button events in DataList items
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 OnItemCommand handler determines what button was clicked, and — if it was the shopping cart button — performs the appropriate logic. The following shows the declaration of the DataList commmand in HTML view, including the ItemTemplate with the ImageButton control:
<asp:DataList id="DataList1" runat=server OnItemCommand="DataList1_OnItemCommand" > <template name="ItemTemplate"> <%# DataBinder.Eval(Container.DataItem, "ItemName") %> <asp:ImageButton runat="server" id="btnShopCart" Command="AddToCart" ImageURL="shopcart.gif" /> </template> </asp:datalist>
The following shows the event-handling method for the OnItemCommand method:
[C#]
protected void DataList1_OnItemCommand(object Source,
DataListCommandEventArgs e)
{
string cmd = ((ImageButton)e.CommandSource).Command;
if(cmd == "AddToCart"){
int RowIndex = (int)e.Item.ItemIndex;
// Logic here to add item to shopping cart
}
}
Introduction to the DataList Web Control | Allowing Users to Delete Items | Allowing Users to Edit Items | Allowing Users to Select Items