Roshan
Roshan

Reputation:

ASP.NET - Dynamically created button

I have added a dynamically created button in my Webform. But its click event is not working. Can anyone please explain why?

This is my code:

    Button save = new Button();
    save.ID = "btnSave";
    save.Text = "Save";
    save.Click += new System.EventHandler(this.Save_Click);
    Webform.Controls.Add(save);

protected void Save_Click(object sender, EventArgs e)
{

    Response.Redirect("Default.aspx");
}

Its coming back to the same page itself. It is not redirecting to Default.aspx.

Upvotes: 1

Views: 2126

Answers (2)

womp
womp

Reputation: 116977

Your code example is not complete enough for a diagnosis, but I'll take a shot at it.

At what point in the page lifecycle are you adding the button to the page? If you're doing it in PreRender, that is why it is not working. You should be doing it during Init.

UPDATE:

You can't dynamically create a control after the Init phase of the page lifecycle and get it to work properly, unless you create it the same way every single time. This is because the lifecycle looks like this:

Init -> Load ViewState -> Page Load -> Event Handlers -> PreRender.

You are creating a button and giving it an event handler during the second last phase. This means that the button is never registered to save it's ViewState with the page, and therefore all state for that button is not restored when it is clicked - meaning that your assigned event handler disappears into thin air, and will never be called.

My suggestion would be to create the Save button normally on the page (not dynamically), and simply set it Visible="False". Then, on the Click handler of your first button, just set your Save button Visible="true".

Upvotes: 4

Ash Machine
Ash Machine

Reputation: 9901

Can you debug this and determine if the code even gets to the click event, or, is there a problem with your Redirect? Womp is correct, bind the event in Page_Init.

Upvotes: 0

Related Questions