Accessing controls in OnPreInit method might be tricky when MasterPage is used

Today I've come across an odd problem. I had to set SkinID property of a control dynamically and this step can be achieved only during PreInit event (OnPreInit method). It is a no brainer implementing the code on standalone Page.

protected override void OnPreInit(EventArgs e) { SomeControl.SkinID="TuboSkin"; base.OnPreInit(e); }

But when the page is hosted on MasterPage the code above throws a Object reference not set to an instance of an object, yep, SomeControl is null for some reason that has to do with MasterPage composition. After googling around for quite some time I've found the solution and explanation to the problem, thanks to Simon's post. The solutions is to call Page.Master property before accessing any of the controls, like this:

protected override void OnPreInit(EventArgs e) { System.Web.UI.MasterPage dummy = Master; SomeControl.SkinID="TuboSkin"; base.OnPreInit(e); }

Leave a Reply