Wednesday, April 4, 2012

Capture Button click events in a DataList


Asp.Net - Capture Button click events in a DataList

A DataList control in Asp.net is similar to a Repeater control with a few additional features, the DataList control provides us the ability to define ItemTemplate and EditItemTemplate, therby allowing us to Edit the content of a specific Item in the DataList.

Apart from the default EDIT & DELETE options, we can also add custom buttons to the DataList and the click event of these buttons can be handled using the ItemCommand event of the DataList.
Let us see an example where we add a Button to the Footer of a DataList and handle its click event using the ItemCommand event of the DataList.

<asp:DataList ID="dlSample" runat="server"
          onitemcommand="dlSample_ItemCommand">
          <ItemTemplate>
                   <table>
                             <tr>
                                      <td> Add Controls Tags Here</td>
                             </tr>
                   </table>
          </ItemTemplate>
          <FooterTemplate>
                             <asp:Button ID="cmdHello" runat="server" Text="Click Me"
                             CommandName = "SayHello"/>
          </FooterTemplate>     
</asp:DataList>


Now we have the button defined in the .aspx page, we shall not capture the click event of the button in the code behind file.

protected void dlSample_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "SayHello")
        {
Response.Write(“Clicked on Button Hello !!!”);
        }
    }


That’s it, we have added a custom button to the DataList control and handled its Click event.

Search Flipkart Products:
Flipkart.com

2 comments:

Arjun.Y.K said...

Its Working..... Thank You

Unknown said...

It's Work but, If there is a Linkbutton then it's not working.
Please Reply