Example
1. The ASPX Markup
In this example, we have two buttons in the ItemTemplate. One utilizes a predefined command ("Edit"), and the other uses a custom command ("AddToCart"). We also use CommandArgument to pass the unique ID of the record so the server code knows which row to affect.
html
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<!-- Display bound data -->
Name: <%# Eval("ProductName") %> <br />
<!-- Predefined command button -->
<asp:Button ID="btnEdit" runat="server"
Text="Edit Item"
CommandName="Edit" />
<!-- Custom command button -->
<asp:Button ID="btnCart" runat="server"
Text="Add to Cart"
CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:DataList>
Use code with caution.
2. The Code-Behind (C#)
In your server-side code, you write a single method to handle the OnItemCommand event. The DataListCommandEventArgs e object supplies the CommandName and CommandArgument from the clicked button.
csharp
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
// Check which command name was sent
if (e.CommandName == "Edit")
{
// Put the clicked row into edit mode
DataList1.EditItemIndex = e.Item.ItemIndex;
BindData(); // Rebind your data source to update the view
}
else if (e.CommandName == "AddToCart")
{
// Extract the unique ID passed from the CommandArgument
string productId = e.CommandArgument.ToString();
// Execute your custom logic
AddProductToCart(productId);
}
}
Key Takeaways
- Centralization:
CommandName funnels your user interactions into a single block of server-side logic (ItemCommand), rather than managing individual button pointers.
- Pairs with CommandArgument: While
CommandName tells the server what action to take, the CommandArgument property tells the server which record to take that action on.