Access nested controls in ASP.NET Page PreInit event (when no Master Page is involved)

There’re situations when you need access ASP.NET web controls very early in page lifecycle, more specifically – in Page PreInit event – and you can, but only top-level controls. But what if you need to access child/nested controls? The example below uses Infragistics WebHierarchicalDataGrid as a child of Infragistics WebSplitter, but this pretty much applies to any such scenario.

Let’s say you have following layout

<ig:WebSplitter ID="WSP" runat="server">
   <Panes>
      <ig:SplitterPane runat="server">
         <Template>

            <ig:WebHierarchicalDataGrid ID="WHG" runat="server">
            </ig:WebHierarchicalDataGrid>

         </Template>
      </ig:SplitterPane>
      <ig:SplitterPane runat="server"></ig:SplitterPane>
   </Panes>
</ig:WebSplitter>

As you can see grid “WHG” is nested withing first pane of splittet “WSP. Let’s see what happens if you try access the controls in PagePreInit event:

Protected Sub Page_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
  
   'accessing some basic properties
   Dim sID1 As String = WSP.ID  'this works
   Dim sID2 As String = WHG.ID  'this throws NullReference exception

End Sub

If you run this code, you will realize that top-level/container control WSP is available along with all its properties, so Line 4 executes fine. But but variable WHG that should hold reference to nested/child control has value of Nothing (or null, for all you, C#-heads) so “Object Reference Not Set” error is thrown in Line 5.

I have seen similar scenarios were Master Page is involved and you can Google numerous solutions to this one. But in this case there is no Master Page. But, there’s a way to make the child control available. Let’s change the code a little bit:

Protected Sub Page_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
  
   'accessing some basic properties
   Dim sID1 As String = WSP.ID  'this works
   WSP.FindControl("WHG") '*** force page to look for the control
   Dim sID2 As String = WHG.ID  'now this also works

End Sub

As you can see we added one more line, asking parent control to do a lookup for child control. We’re not assigning result to anything (and it can even return Nothing) but after that line is executed – variable representing child control will actually have reference to child control and the code runs without an exception.

Leave a Reply

Your email address will not be published. Required fields are marked *