Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the OnInit event in asp.net

Tags:

c#

asp.net

I have contentpage overriding the OnInit event of a masterpage. The override works fine, until I put a custom user control on the page: in this case the OnInit event does not fire for the contentpage (no overrides are used in the user control)

What are the possible causes/solutions for this? (I use the OnInit event to create dynamic controls)


Edit:

now i tried this in the content page:

(The OnPreInit part runs, but Masters_Init does not get called...)

    protected override void OnPreInit(EventArgs e)
    {
        base.Master.Init += new EventHandler(Masters_Init);
    }

    void Masters_Init(object sender, EventArgs e)
    { 
    //code 
    }
like image 260
akosch Avatar asked Mar 20 '09 19:03

akosch


1 Answers

Are you calling the base.OnInit?

public override void OnInit(EventArgs e)
{
  // code before base oninit
  base.OnInit(e);
  // code after base oninit
}

Update

public class Page1 : Page
{
  public Page1 : base() {
    PreInit += Page_PreInit;
  }
  void Page_PreInit(object sender, EventArgs e)
  {
    Master.Init += Master_Init;
  }
  void Master_Init(object sender, EventArgs e)
  {
    //code
  }
}

Also as mentioned in the comments I would recommend not overriding the events if you don't have to, but if you must be sure to call the base. so in your edit above it should be

protected override void OnPreInit(EventArgs e)
{
  base.OnPreInit(e);
  base.Master.Init += new EventHandler(Masters_Init);
}
like image 178
bendewey Avatar answered Sep 24 '22 16:09

bendewey