NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Responding to Button Events in DataList Items

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

  1. Include a Button, LinkButton, or ImageButton in a DataList template. Set the button's Command property to a string that identifies its function, such as "sort" or "copy".
  2. Create a method for the OnCommandEvent event of the DataList control. In the method, do the following:
    • Check the Command property of the event-argument object's CommandSource to see what string was passed. If you are testing for a number of possible strings, use a Select Case (Visual Basic) or switch (C#) statement or equivalent.
    • 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 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")  %>
             &nbsp;
             <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
       }
    }
    

See Also

Introduction to the DataList Web Control | Allowing Users to Delete Items | Allowing Users to Edit Items | Allowing Users to Select Items