Accessing Controls in a DIV with the runat=server attribute

When you use the runat=”server” attribute with a div tag in asp.net, any controls nested in the div will not be accessible directly via the page’s Controls collection. They will be in the Controls collection of the div.
For example, in the code section below:

<body>
<form id="form1" runat="server">
<asp:RadioButtonList ID="RadioButtonList4" runat="server" Width="250px"/>
<div runat="server" id="section_1" style="display:block;">
Instructor 2

<asp:DropDownList ID="InstructorDropDown2" runat="server"></asp:DropDownList>
</div>
</form>
</body>

the value in the RadioButtonList1 control can be accessed from code-behind with this.form1.RadioButtonList4.SelectedValue; however, the nested control InstructorDropDown2 cannot be accessed the same way: this.form1.InstructorDropDown2.SelectedValue will not work. You have to use  this.section_1.InstructorDropDown2.SelectedValue, i.e. accessing it via the parent div tag!

I discovered this after a long series of frustrating attempts to access controls in the show-hide section of a page while I was developing for a survey application.

Related Posts

Unresolved Assembly Reference when Merging Precompiled ASP.NET Assemblies

If you need to merge the output DLLs generated after precompiling an ASP.NET website from Visual Studio 2008 and later, you need to use the ASP.NET merge tool. The location of this tool is a bit tricky, though. The version in the default location is actually the wrong one!

FilterExpression in ASP.NET SqlDataSource

The FilterExpression tag in ASP.NET does not support the between operator. If you try to specify a clause like “between x and y” as your filter expression,…