tags:

views:

253

answers:

2

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.

+3  A: 

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".

womp
I am doin it at a button click
You're creating another button on button click?
John Sheehan
ya im creating another button on the button click and this is the newly created button's event handler.
That will not work. I'll update my answer to explain why.
womp
But i have some Labels and Textboxes which are being added to the page dynamically. I want to place the button control after the dynamic contents are added to the page. So how do I that?
Setting the visibility seems like a good answer to me. If you can deterministically add the button to the page via code, it means it doesn't have to be dynamically loaded in the first place. It's visibility/enabledness seems to be the dynamic element. Continued...
Daniel Auger
Adding controls dynamically is something you usually do when you know you have to add *something* to the page that could change via configuration etc... If the button just needs to be conditionally on or off then use visible. Of course there are always exceptions to that, but I do like this answer.
Daniel Auger
A: 

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.

Ash Machine