Search code examples
c#asp.netfindcontrol

FindControl suddenly returning object reference error (ASP.NET/C#)


I have the following code in my Global.asax file:

System.Web.UI.Page webPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
string date = ((Literal)webPage.FindControl("ltlGenTime")).Text;

The control definitely exists on the webpage, and I've verified this by checking the webPage object and its base class, and it's definitely a literal control.

Now I have made a change which seems to have caused this - I created a master page for all my pages. But I'm confused as the webPage object still has the control I require listed.

Any ideas?


Solution

  • Master pages modify the page control hierarchy, so first you need find the content placeholde from master and then locate the actual control - for example,

    Master.FindControl("YourContentPlaceholderId").FindControl("ControlName");
    

    See this article for more info.