Search code examples
c#asp.netgridviewrowcommand

LinkButton's not firing GridView_RowCommand


I have a LinkButton inside a GridView that passes a CommandArgument and tries to fire RowCommand

GridView declaration:

<asp:GridView PageIndex="0" OnRowCommand="GridView1_RowCommand" PageSize="10" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Width="700px"
AutoGenerateColumns="False" OnPageIndexChanged="GridView1_PageIndexChanged">

LinkButton inside the GridView:

<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('Are you sure you want to delete this checklist?');" runat="server" CausesValidation="false" CommandName="DeleteChecklist" CommandArgument='<%# Eval("refID") %>' Text="Delete"></asp:LinkButton>
    </ItemTemplate>
    <ItemStyle ForeColor="Black" />
    <ControlStyle BorderStyle="None" ForeColor="Black" />
</asp:TemplateField>

Code behind:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "DeleteChecklist")
    {
        string refID = e.CommandArgument.ToString();
        DAL.DeleteChecklist(refID);
     }
}

I placed a breakpoint at RowCommand but it doesn't get fired at all, any idea why?


Solution

  • I assume that you're databinding the GridView on postbacks. So always embed it in a if(!IsPostBack) check:

    protected void Page_Load(Object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
             GridView1.DataSource = getSource();
             GridView1.DataBind();
        }
    }
    

    Otherwise events won't be triggered and edited values will be overridden.

    Another possible reason: Have you disabled ViewState?