If you're developing websites, sooner or later you will be asked to produce a list of data where each row will need to have a button on it that performs a function. If you need to do this in a Repeater and are wondering how to achieve this then read on.

For this example I will assume you know what a repeater is and are familiar with how to binding data to it from a database or similar.

In your page you would have a repeater. Below is a sample that I'm going to use for this example:

<asp:Repeater ID="MyRepeater" OnItemCommand="WhatToDo_ItemCommand" runat="server">
<ItemTemplate>
<ul>
    <li><%# Eval("ItemName")%></li>
    <li><%# Eval("ItemDetails")%></li>
    <li><asp:LinkButton ID="DeleteItem" CommandArgument='<%# Eval("ItemID") %>' CommandName="DeleteThisItem" runat="server">delete this item</asp:LinkButton></li>
    <li><asp:LinkButton ID="UpdateItem" CommandArgument='<%# Eval("ItemID") %>' CommandName="UpdateThisItem" runat="server">update this item</asp:LinkButton></li>
</ul>
</ItemTemplate>
</asp:Repeater>

Nothing to out of the ordinary here. There are a few things to note. In your <asp:repeater> tag you must include the class you want to call when the button is clicked. This is the OnItemCommand="WhatToDo_ItemCommand" bit. You will see in a few mins where this is used. Next up is the code that puts the ID value into the buttons you're going to use. CommandArgument holds the value for your command, in this case it's going to hold our database row ID and CommandName is needed so that our code will know which button made the call.

Next up is the code behind page:

//code to handle button clicked within repeater
protected void WhatToDo_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{
     e.CommandArgument.ToString(); //value of link
     if (e.CommandName == "UpdateThisItem")
     {
          //do your update details here
     }
     if (e.CommandName == "DeleteThisItem")
     {
          //do your delete details in here
     }
}

In the code view you can see that we have a class that is called the same name as the OnItemCommand value in our repeater (WhatToDo_ItemCommand). You should also be able to easily see that we can check e.CommandName for the name of which button we want to run. Obviously if you plan on having a lot of buttons you would be better off using switch statement instead of if statements but the above is only meant to act as a sample for you to get going.

If you use a DataList you can substitute RepeaterCommandEventArgs to DataListCommandEventArgs and be sure to put the OnItemCommand in your DataList tag to get the same results.