Accessing Controls in a DIV with the runat=server attribute

When you use the runat=”server” attribute with a div tag in, 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:

<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>

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.

Leave a comment