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

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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


Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rito1Author Commented:
Thanks Alfred1, I am just giving it ago.
Have you tried .FindControl("ContentPlaceHolder1_PlaceHolderQuestions" ... ?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.