SunVigna
SunVigna

Reputation: 77

Dynamically created button not firing Click event

I am creating dynamic controls, in that one control is a button. I used the following code to add the button control.

Button btnContinue = new Button();
btnContinue.Attributes.Add("class", "button");
btnContinue.ID = "btnContinue";
btnContinue.Text = "Continue";
btnContinue.CausesValidation = false;
btnContinue.Click += new EventHandler(btnContinue_Click);                
lineAdd.Controls.Add(btnContinue);

And the button click event as below.

protected void btnContinue_Click(object sender, EventArgs e)
{
    ...
}

This event is not firing. Any idea why this is not firing the event. Please correct me if i am wrong.

Thanks in Advance.

Upvotes: 0

Views: 13306

Answers (3)

p4bl0
p4bl0

Reputation: 5633

You MUST initialize dynamically created controls inside the OnInit() method (see MS kb post), or the page will not consider it. Note that the control must be created also during the postback caused by the control itself.

Upvotes: 1

Shai
Shai

Reputation: 25619

Try setting the UseSubmitBehavior property to True.

Upvotes: 0

BritishDeveloper
BritishDeveloper

Reputation: 13349

Make sure your are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.

This is because the event handling events happen after Page Init. Of course the button has to have been created before the events can detected on it. The joy of web forms...

Upvotes: 4

Related Questions