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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With