简体   繁体   中英

GridView RowCommand event not firing

I have a GridView that looks something like this:

<asp:GridView 
    ID="GridView1"
    AllowPaging="true"
    OnRowCommand="RowCommand"
    OnPageIndexChanging="gridView_PageIndexChanging"
    Runat="server">
    <Columns>
        ...
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" ButtonType="Button" CommandName="ItemExport" CommandArgument='<%# Eval("EXPORT") %>'
                    Text="Export" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
 </asp:GridView>

Here is RowCommand :

protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ItemExport")
    {
        // etc.
    }
}

Clicking the button is not firing the RowCommand event at all. However, RowCommand fires when I click a page index in the GridView's pager.

You must not bind your grid on postbacks in Page_Load, only when something changed that causes the Grid to reload data(fe Sorting,Paging) and only in the appropriate event-handlers.

Another possible reason: Have you disabled ViewState somewhere?

Use CausesValidation="false" in button tag. It can solve the problem.

I just had a colleague who encountered the same problem; his was caused by the onrowcommand= attribute not being set in the asp:GridView element. This should be set to the name of the handler which will be handling the event.

... just in case someone has the same issue!

Put the grid.Databind() inside if (!IsPostBack)

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        grid.DataBind();
    }
}

If your code is like this:

protected void Page_Load(object sender, EventArgs e)
{
    BindGrid(dgv);
    if (!IsPostBack)
    {

    }
}

Put BindGrid() inside the !isPostBack block

Tried the above answers and still could not get a post back. Ended up being a Unique ID issue. I had two <ItemTemplate> with buttons that had the same ids. (In different grid views. My second one was in a User Control)

Changing the <asp:Button ID="" /> to a Unique ID solved the post back issue for me.

Just thought I'd post for any one else who tried the other options with no luck.

您还可以检查 HttpContext.Current.Request.Form["__EVENTTARGET"] ,如果它以控件的 ID 结尾,则重新绑定 GridView 并使用带有事件目标的 Page.FindControl 来查找触发事件的控件

My problem was requiredfieldvalidator

Solution to that was: I disable it at post back and then re-enable it after the row command.

他们都做了但一无所获然后发现了这一点:onrowcommand="GridView1_RowCommand" 在 html 的 GridView1 定义行上。

我通过从 GridView 中删除所有事件处理程序,然后重建代码,然后一次将它们添加回一个来修复我的这个问题版本。

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