R – Gridview inside Repeater not firing Delete Event

asp.netgridviewrepeater

I have a Repeater that has a gridview in it, which uses an SqlDataSource with a delete command. When I click delete on a given row, it posts back but doesn't fire the delete. Am I forgetting something?

Best Answer

Have you set the GridView's DataKeyNames property? It needs to be set to the item's primary key to uniquely identify the record to modify. If you didn't set it, clicking Delete (or Edit) would cause a postback that doesn't affect anything since a DataKey wasn't associated with each GridView row.

According to the GridView.DataKeys property page:

When the DataKeyNames property is set, the GridView control automatically creates a DataKey object for each row in the control. The DataKey object contains the values of the field or fields specified in the DataKeyNames property.

For example, let's say you're deleting a product item that's identified by a ProductID field.

Your SqlDataSource might look something like this:

<asp:SqlDataSource ID="ProductsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
SelectCommand= "SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]" 
DeleteCommand="DELETE FROM Products WHERE ProductID = @ProductID">
    <DeleteParameters>
      <asp:Parameter Name="ProductID" />
    </DeleteParameters>
</asp:SqlDataSource>

You would then assign the same "ProductID" primary key to the GridView's DataKeyNames property:

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
        DataKeyNames="ProductID" ...

These tutorials may be helpful to you:

Related Topic