0

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>

2 Answers2

1

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");
Mahmoude Elghandour
  • 2,921
  • 1
  • 22
  • 27
  • you can not `FindControl` with `GridViewCommandEventArgs` like this. Follow this [answer](http://stackoverflow.com/a/27159747/2374691) to know how to access `FindControl` properly – Ritwik Jul 09 '15 at 12:05
0

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.

Ritwik
  • 521
  • 7
  • 17