javascript ASP.NET Gridview ButtonField onclick 触发包含行的 onclick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21131048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:09:04  来源:igfitidea点击:

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

c#javascriptjqueryasp.netgridview

提问by Vincent Rakau Majatladi

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.

我有一个 gridview 行,单击时必须执行回发 A,该行中有一个按钮字段,单击时必须执行回发 B。问题是当我单击按钮字段时,event1 和 event2 都会被触发。下面是代码。

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

这是gridview的asp代码

<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>

回答by Mahmoude Elghandour

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

回答by Ritwik

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

<asp:TemplateField>如果您不想要单独的标题,请尝试添加两个按钮

<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.

如果您想要单独的标题,请制作两个单独的标题<asp:TemplateField>,然后在其中添加按钮。