Object reference not set to an instance of an object and INamingContainer

A list of standard ASP.NET web controls that implement INamingContainer

Any control that implements the INamingContainer interface creates a new control namespace which ensures that child controls have unique names on the page. If you try to directly access, for example, a TextBox within a FormView without using the FormView's FindControl() method, you will receive an "Object reference not set to an instance of an object" error. An excellent explanation of this behaviour and the FindControl() method is provided by K Scott Allen, and I won't attempt to replicate the basis of his article here. Instead, here is a list of all the standard ASP.NET web controls (System.Web.UI.Controls) that implement INamingContainer with which the FindControl method needs to be used:

  • ChangePassword
  • CheckBoxList
  • CreateUserWizard
  • DataGrid
  • DataList
  • DetailsView
  • FormView
  • GridView
  • ListView
  • Login
  • LoginView
  • LoginStatus
  • Menu
  • PasswordRecovery
  • RadioButtonList
  • SiteMapPath

There is one addition to the above list - ContentPlaceHolder - when working with MasterPages. For example, to reference a label in a FormView in a ContentPlaceHolder, you need to do something like the following:

Label lbl = this.Content1.FindControl("FormView1").FindControl("Label1") as Label;