ASP.NET 2.0: Accessing dynamic controls from content page when you have nested master pages.

Recently I got a problem where the customer was trying to access dynamically created controls from a content page while using nested master pages. I thought it would be a cakewalk only to get slightly confused while working out a small sample to demonstrate how to access the dynamic control. So here is a brief overview about the Troubleshooting.

Customer was developing an ASP.NET 2.0 application which had nested master pages. Part of the requirement for this application was that one of the pages was rendering the rows and columns for a table dynamically based on user input on the same page. Also the customer wanted to add a list of radio buttons to the table rows and access the selected item in another button click event.

So if I have a dynamic control called rbtnDynamic and if i need to get the value of this control in another event, this is how i will need to access it.

 rbtnlNew = (RadioButtonList)Master.Master.FindControl("cphParent").FindControl("cphChild").FindControl("rbtnlDynamic");
Response.Write(rbtnlNew.SelectedItem.Value.ToString());

This may look to be a weird way of fetching the value of the radio button, but take a look at the control tree below and it will make more sense to you.

Control Tree

 

As you can see the Page itself is the container for the Child Master which in turn acts as a container for the Parent Master, thats why we need to first back track and locate the content place holder for the parent master, then come down to the child master and finally do a FindControl for the control itself.

Hope that makes things clearer :-)