Parvez M Robin Parvez M Robin - 4 months ago 32
C# Question

Click Event Handler of ASP.Net Button in User Control is not Working

My User Control in my ASP.Net application has a Button named button. I've added a click event to it like this:

protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
button.Click += (object o, EventArgs ea) => {
Response.Redirect("~/Post.aspx?type=" + Type + "&id=" + PostID);
};
}
}


But whenever I click on the Button it does nothing but reloads the page. What is the problem with my code?

Answer

You should remove the if (!IsPostBack) condition to set the event handler on every postback:

protected void Page_Load(object sender, EventArgs e) {
    button.Click += (object o, EventArgs ea) => {
        Response.Redirect("~/Post.aspx?type=" + Type + "&id=" + PostID);
    };
}