简体   繁体   中英

ASP.NET Gridview ButtonField onclick fires containing row's onclick event

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>

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");

Try adding both the button with in same <asp:TemplateField> if you don't want separate headers

<Columns>
  <asp:TemplateField>
    <ItemTemplate>

       <asp:Button ID="button" runat="server" CommandName="Command1" />
       <asp:LinkButton ID="btn1" runat="server" CommandName="Command2" />

     </ItemTemplate>
 </asp:TemplateField>
</Columns>

if you want separate headers make two separate <asp:TemplateField> and then add buttons in them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM