Javascript – ASP.NET Gridview ButtonField onclick fires containing row’s onclick event

asp.netcgridviewjavascriptjquery

I have a gridview row that when clicked has to do postback A and a buttonfield in that row that when clicked has to do postback B. The problem is that when i click on the buttonfield, both event1 and event2 gets fired. Below is the code.

protected void gdv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    string arg = Convert.ToString(((System.Web.UI.WebControls.CommandEventArgs)(e)).CommandArgument);

    if (e.CommandName == "Command1")
    {
        doEvent1(arg);
    }
    else if (e.CommandName == "Command2")
    {
        doEvent2(arg);
    }
}

protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {            
        LinkButton b1 = (LinkButton)e.Row.Cells[0].Controls[0];
        matchesButton.CommandArgument = arg1;

        LinkButton rowLink = (LinkButton)e.Row.Cells[1].Controls[1];
        rowLink.CommandArgument = arg2;

        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(rowLink, "");
    }
}

And this is the asp code for the gridview

<Columns>
    <asp:ButtonField DataTextField="f1" HeaderText="H1" CommandName="Command1" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="btn1" runat="server" Text="" CommandName="Command2" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

Best Answer

try to use this

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Command2")
    {
       // Your Code here
    }
}

to find control in grid view use this code

LinkButton lnkbtn= (LinkButton)e.Row.FindControl("btn1");