Kizz
Kizz

Reputation: 799

ASP.NET: Page.Init woudln't fire

I have a custom ASP.NET control. In its Init handler I add a delegate to the Page's Init like this:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if(someCondition())
    {
            this.Page.Init += delegate(object sender, EventArgs ee)
            {
                //some stuff
            };
    }
}

Now, if I add this custom control to the HTML of the page declaratively, every thing works fine, the Page's Init delegate gets called. But if I add this control to the page programmatically like:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    MyControl myControl = new MyControl { ID = "myControl" };
    this.Page.Form.Controls.Add(myControl);
}

The Init if the control get's called but the delegate that I attached to the Page.Init does not. What am I doing wrong here?

Upvotes: 3

Views: 1010

Answers (3)

user766279
user766279

Reputation:

Move the declaration of your custom control to page's OnInit instead of OnLoad. Instantiate your control and add it to the form before calling base.OnInit(e). This will give the page chance to load your control and actually attach your delegate to page's Init event before the Init gets called by the ASP.NET run time. Your problem is that page's Init was already called when your control's Init gets executed.

Upvotes: 2

Leon
Leon

Reputation: 3401

Instead of adding control in PageLoad, add it in Page_PreInit event handler.

Upvotes: 1

Martin
Martin

Reputation: 1536

IT's because when adding the controls in OnLoad the Page's Init has already executed

Upvotes: 3

Related Questions