ASP.net Null Reference Exception Due to Not Finding Controls

后端 未结 1 2026
Happy的楠姐
Happy的楠姐 2021-01-29 15:22

I am having this exception that I can\'t figure out why it is happening. I searched this site and others trying to find a solution but none have worked so far.

The Prob

相关标签:
1条回答
  • 2021-01-29 15:50

    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.

    0 讨论(0)
提交回复
热议问题