I have a custom ASP.NET control. In its Init handler I add a delegate to the P开发者_Python百科age'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?
IT's because when adding the controls in OnLoad the Page's Init has already executed
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.
Instead of adding control in PageLoad, add it in Page_PreInit event handler.
精彩评论