Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get control in ASP.NET PreInit event?

How to get control in ASP.NET PreInit event? Pointers are null and FindControl method returns null.

I am using master and content pages. Markup of the content page looks like this:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentBody" runat="server">
   <asp:Table ID="Table1" runat="server" Width="100%">
      .....
   </asp:Table>
</asp:Content>

And code like this:

private void Page_PreInit(object sender, EventArgs e)
{
    Control table = this.FindControl("Table1");
    //table is null here
}

So table still is null after this.FindControl("Table1"). NamingContainer of the page is null too. What am I doing wrong?

UPDATE I have to use this event to create controls. As said in the ASP.NET Page Life Cycle Overview this event should be used for dynamic control creation. I need to create a list of links in my table. May be there is another way to do it?

like image 395
brain_pusher Avatar asked Jul 01 '10 15:07

brain_pusher


3 Answers

PreInit is fired before the controls are initialized. Read up on the ASP.NET Page Life Cycle for more detailed information.

Init
Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.

Use this event to read or initialize control properties.

like image 198
Shawn Steward Avatar answered Oct 29 '22 21:10

Shawn Steward


In the PreInit() event, standard (defined) controls have not been created yet at that stage, thus you cannot get any reference to any controls.

Use the Page_Load() event to create dynamic controls. During this event, you can add any dynamic controls into existing controls.

After creating the dynamic controls in Page_Load(), use the PreRender() to make any changes/updates.

Personally, I use PreInit to define page wide objects (ie, database connections, user session objects) and also where I perform security authentication checks (and redirects if not authorized) only.

like image 32
Joseph Lee Avatar answered Oct 29 '22 21:10

Joseph Lee


The Page's PreInit event is triggered before the controls are initialized, so controls do not exist yet. You will have to access the control in a later event, such as the Page's Load event. Please see http://msdn.microsoft.com/en-us/library/ms178472.aspx.

like image 34
Halcyon Avatar answered Oct 29 '22 21:10

Halcyon