Udostępnij za pośrednictwem


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

Comments

  • Anonymous
    March 13, 2007
    Hi, It looks good, But I am not able to find the control created Dynamically. Will you please tell me, What is the correct way to create the control dynamically? I am creating it in Page_Init event. How should i assign the value?

  • Anonymous
    March 13, 2007
    If you are already creating the control in Page_Init, you should be able to assign the value there itself, unless you are planning to assign a value in one of the Postback events etc. If that is the case, the above code will stick true. So if you look at the code snippet and lets say you are creating a TextBox dynamically in the Page_Init, so in the Postback back event you can do the following. TextBox txt2; txt2 = (TextBox)Master.Master.FindControl("cphParent").FindControl("cphChild").FindControl("MyTextBox"); txt2.Text = "Hello World!!"; Where "MyTextBox" will be the ID that you need to assign to the textbox when you create it. Hope that helps!!!