Search code examples
asp.netbuttononclickitemtemplate

asp button on click inside item template not firing


Not able to make this work.

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="btnApprove" runat="server" Text="Approve" OnClick ="btnApprove_Click" />
    </ItemTemplate>
</asp:TemplateField>

code behind:

protected void btnApprove_Click(object sender, EventArgs e)
{
    Response.Redirect("viewprofile.aspx");
}

not even firing when button is clicked. any tricks on this?


Solution

  • Set EnableEventValidation="false" right at the top in your Page directive:

    <%@ Page EnableEventValidation="false" Language="C#"...

    Just beware that setting this value to false can expose your website to security vulnerabilities.As an alternative, instead of setting EnableEventValidation="false" you can handle the grid views OnRowCommand:

    .ASPX:

    <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button runat="server" Text="Approve" CommandName="Approve" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    

    Code behind:

    public partial class delete_me : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)//THIS IS IMPORTANT.GridView1_RowCommand will not fire unless you add this line
            {
                var p1 = new Person() { Name = "Person 1" };
                var p2 = new Person() { Name = "Person 2" };
    
                var list = new List<Person> { p1, p2 };
                GridView1.DataSource = list;
                GridView1.DataBind();
            }
    
        }
    
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            System.Diagnostics.Debugger.Break();
        }
    }
    
    public class Person
    {
        public string Name { get; set; }
    }