• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 844
  • Last Modified:

FindControl for Dynamic created Page controls

Hi All,

I am receiving the good old 'Object reference not set to an instance of an object.' error at  the moment when trying to use the FindControl within my code behind.

Here is what my Control Tree looks like when Trace is enabled:


The PlaceHolder control PlaceHolderQuestionType has been created manually and is there at development time.

ctl00$ContentPlaceHolder1$PlaceHolderQuestions and ctl00$ContentPlaceHolder1$phControlContainer are created dynamically within my code behind.

When trying to use the FindControl function like within my code attached I get 'Object reference not set to an instance of an object' which is referring to phControlContainer.

Can anyone see what I could be doing wrong?



PlaceHolder PlaceHolderQuestions = (PlaceHolder)PlaceHolderQuestionType.FindControl("PlaceHolderQuestions");

PlaceHolder phControlContainer = (PlaceHolder)PlaceHolderQuestions.FindControl("phControlContainer");

Open in new window

1 Solution
Alfred A.Commented:
You could try using a FindControlRecursive function if you want.  You can call it something like this as an example

PlaceHolder PlaceHolderQuestions = (PlaceHolder)FindControlRecursive(PlaceHolderQuestionType,"PlaceHolderQuestions");
public Control FindControlRecursive(Control Root, string Id)
            if (Root.ID == Id) 
                return Root;

            foreach (Control Ctl in Root.Controls)
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            return null;

Open in new window

rito1Author Commented:
Thanks Alfred1, I am just giving it ago.
Have you tried .FindControl("ContentPlaceHolder1_PlaceHolderQuestions" ... ?

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now