How to: Respond to Button Events in DataList, Repeater, or GridView Items

Switch View :
ScriptFree
ASP.NET 
How to: Respond to Button Events in DataList, Repeater, or GridView Items 

If your DataList, Repeater, or GridView control template includes Button, LinkButton, or ImageButton Web Server controls, these buttons can send their Click events to the containing DataList, Repeater, or GridView control. This allows you to include buttons for functions not already defined for the DataList and GridView controls (edit, delete, update, and cancel) and to define functionality for the Repeater control.

To respond to button events in DataList, Repeater, and GridView controls

  1. Include a Button, LinkButton, or ImageButton in a control template.

  2. Set the button's CommandName property to a string that identifies its function, such as "sort" or "copy".

  3. Create a method for the ItemCommand event of the containing control. In the method, do the following:

    1. Check the CommandName property of the event-argument object to see what string was passed.

    2. 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 ItemCommand event handler determines which button was clicked, and — if it was the shopping cart button — performs the appropriate logic.

    Visual Basic
    Protected Sub DataList1_ItemCommand(ByVal source As Object, _
            ByVal e As DataListCommandEventArgs)
        If e.CommandName = "AddToCart" Then
            ' Add code here to add the item to the shopping cart.
            ' Use the value of e.Item.ItemIndex to find the data row
            ' in the data source.
        End If
    End Sub
    

    C#
    protected void DataList1_ItemCommand(object source, 
        DataListCommandEventArgs e)
    {
       if (e.CommandName == "AddToCart")
       {      
          // Add code here to add the item to the shopping cart.
          // Use the value of e.Item.ItemIndex to find the data row
          // in the data source.
       }
    }
    

For an example using the DataList Web server control, see How to: Allow Users to Select Items in DataList Web Server Controls.

See Also

Community Content

pwinant
Attributes added during ItemDataBound get lost
The problem I have with only calling DataBind on the repeater during the initial load (but not on PostBack) is that I add attributes to some of the items in the 
ItemDataBound event handler:

Dim approvalID As Integer = DataBinder.Eval(e.Item.DataItem, "ApprovalID")
Dim rbl As RadioButtonList = e.Item.FindControl("radApproveOrDecline")
rbl.Items(0).Attributes.Add("OnClick", "show('approve', '" & approvalID & "');")
rbl.Items(1).Attributes.Add("OnClick", "show('decline', '" & approvalID & "');")

Those attributes don't get render during a postback so I lose my javascript. Is there some way to prevent this?

Robert Dunlop
Documentation seems to be lacking on interaction of DataBind with item command postbacks
Thanks Mazrick, after hours trying to track down information to solve this problem, this is the ONLY post I have found that offered this simple solution. Even after reading this, I still can't track anything down on MSDN that would provide an indication that Databind could lead to such an issue. (Hopefully MSDN people will read these contributions?) Is there any documentation that you know of that details this interaction between contol postbacks and the DataBind method?

Mazrick
EventValidation error when using a CommandName from within a Repeater
Possible causes of your trouble:

1. Make sure to bind your Repeater, DataGrid or DataList control only on "Not Page.IsPostBack".
Like this.
If Not Page.IsPostBack Then
...
Repeater1.DataBind()
End If
2. Make sure that there are NO "Page.DataBind()" or other DataBind calls that could be embeded in your controls/MasterPage etc.
If the page is re-databound at the wrong time, it will generate EventValidation errors.


Nate Tregillus
Validation Error on commandName / ItemCommand event combo

I found this un-useful because it causes an invalid postback/callback argument exception.

In the itemTemplate region i placed the following button tag:

 <asp:Button ID="btnReProcessOrder" runat="server" Text="Reprocess Order" CommandName="Process" />

and in the code behind i added the following event to my dataList

    Private Sub dlOrders_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles 												dlOrders.ItemCommand
Dim row As DataRowView
row = CType(e.Item.DataItem, DataRowView)
Select Case e.CommandName
Case "Process"
'process subroutine here
        End Select
End Sub

here is the exact text of the error message:

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation

Is there something i am missing? do i actually have to turn off page validation just to get this ItemCommand to work? i find that silly.

Thanks,

Nate