Getting Strongly-Typed Control References out of LoginViews–without using FindControl()

Today I was working on a rather complex web form that uses a number of LoginView Controls with role-specific templates containing custom UserControls. Now, at first I thought I could just directly reference items within the LoginView’s ContentTemplates. But that is not exactly the case. The ControlTemplates behave as loosely typed ITemplates. Now one could use the trusty old FindControl(string) method to divine the control name. But that always makes me feel a bit icky as it is not typechecked at compile time. Nevermind the potential for errors if, for example, someone changed the ID of the control. Or wrapped it in a parent control thereby hiding it from the control hierarchy. Hello Object Reference Not Set to Instance of Object.

Instead, I realized that one could very easily and cleanly do the following:

  1. In the codefile (or whatever contains the LoginView), create a protected variable of the type of the desired UserControl or custom ServerControl or whatever.
  2. In the control you require a reference to, wire up the OnInit event.
  3. In the handler for the OnInit event map the sender to the variable you created in step #1.

Or if that made no sense, just check out the code samples below:

First the ASPX code:


<asp:LoginView ID="PermissionsLoginView" runat="Server">
	<RoleGroups>
		<asp:RoleGroup Roles="Administrator">
			<ContentTemplate>
				<wwb:UserPermissions 
					ID="UserPermissionsCtl" 
					runat="server" 
					OnInit="UserPermissionsCtl_Init" 
				/>
			</ContentTemplate>
		</asp:RoleGroup>
	</RoleGroups>
</asp:LoginView>

The key item there is the wwb:UserPermissions’s call to OnInit.

And now for the codefile bit:


//Variable to contain the user control reference.
protected UserPermissions UserPermissions = null;

//handler for the UserPermissionsCtl's Init event.
protected void UserPermissionsCtl_Init(object sender, EventArgs e)
{
	UserPermissions = (UserPermissions)sender;
}

I have not tried it with anything aside from LoginView, but it should work for the other multi-template controls (such as MultiView). Enjoy and happy coding.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.dangrossman.info Dan Grossman

    Need to work on this entry’s title a bit. A few errors.

  • wwb_99

    What errors ? :p

  • wwb_99

    Fyi, further testing indicates this does not always work. Stay tuned for an update.