简体   繁体   中英

Asp GridView firing Click event on the entire row

I have a GridView which has ID , Name and Type .

Code behind:

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gridView, "Select$" + e.Row.RowIndex);
    }
}

public void gridView_Command(object sender, GridViewCommandEventArgs e)
{
   // some code here //
}

The GridView :

<asp:GridView ID="gridView" runat="server" OnRowCommand="gridView_Command" />
<columns>
    <asp:BoundField DataField="ID" />
    <asp:HyperLinkField DataTextField="Name" />
    <asp:BoundField DataField="Type" />
</columns>

The Name is click enabled because of the HyperlinkField. The problem here is I don't want the gridview_Command to be triggered if the row is clicked. I just want the Name field. For example, if the column of the Type is clicked, don't fire the gridView_Command .

It is not that clear what you are trying to achieve, but if I understand correctly there are a few things you need to change.

  1. You need to wrap your columns inside of the <asp:Gridview> tag.
  2. You need to hook up your RowDataBound event.
  3. You need to create a template column so you can use the CommandName parameter.
  4. You need to filter for the CommandName parameter in your event to only respond to the click from the control you want.

<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound" OnRowCommand="gridView_Command" AutoGenerateColumns="false" > <columns> <asp:BoundField DataField="ID" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Type" /> </columns> </asp:GridView>

public void gridView_Command(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "NameButton")
    {
        var id = e.CommandArgument;

        // some code here //
    }
}

Using this example, you can respond to the event of a click on the "NameButton" only.

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