[Solved] ASP.net Null Reference Exception Due to Not Finding Controls


In my experience, DIV’s are not registered to the server like ASP controls are so calling them directly would produce bad results. When making changes to the controls, i.e. adding styles, make sure you tell ASP what kind of control you have.

For example:

HtmlGenericControl _fail = (HtmlGenericControl)Page.FindControl("fail");

_fail.Style.Item("visibility") = "hidden";

Edit: The problem lies with the ContentPlaceHolder being nested in the LoginView. Drilling down to the controls should expose them.

Example:

LoginView temp = (LoginView)this.Master.FindControl("LoginView1");
ContentPlaceHolder tempp = (ContentPlaceHolder)temp.FindControl("MainContent");
HtmlGenericControl _fail = (HtmlGenericControl)tempp.FindControl("fail");

If you create some class variables to point to these controls and assign them on page load, you can then call them from wherever you want in your code.

To add further confusion to the solution, if you only add:

LoginView temp = (LoginView)this.Master.FindControl("LoginView1");
ContentPlaceHolder tempp = (ContentPlaceHolder)temp.FindControl("MainContent");

to Page_Load and nothing else, it exposes the controls so you can call fail.Style.Add(“visibility”, “hidden”) directly. There seems to be some delay as to when the controls are enumerated by ASP. Calling FindControls() on LoginView, appears to refresh the control “cache” exposing the controls as you would expect them to be.

6

solved ASP.net Null Reference Exception Due to Not Finding Controls