You are here > Blog

WebF1 Consulting Blog

Nov 1

Written by: Oscar Meszar
11/1/2009 7:16 PM 

While working in SharepPoint I needed, from an UserControl in my WebPart, find a control in the page. Of course, I tried, different level at which to apply the FindControl(). The first thing I tried was this.Parent.Page.FindControl(“controlID”). That didn’t work. Then I tried different permutations. Finally I gave up with the FindControl and decided that I would do it the old fashion way. I’ll walk the tree. Here is some sample code how to do that.

    Control PViewer = null;               
                foreach (Control Ctrl in this.Parent.Page.Controls)
                {
                    PViewer = FindMyControl(Ctrl,”MyControlID”);
                    if (PViewer != null)
                    {
                        break;
                    }
                }

 private Control FindMyControl (Control ctrl, string controlID)
        {
            Control Ret = null;

            foreach (Control Ctrl in ctrl.Controls)
            {          
                if (Ctrl.ID != null && Ctrl.ID.ToLower() == controlID.ToLower())              
                {                  
                    Ret = Ctrl;
                    break;
                }
                else
                {
                    Ret = FindMyControl (Ctrl,controlID);
                    if (Ret != null)
                    {
                        break;
                    }
                }
            }
            return Ret;
        }

 

Of course if you examine the code you will notice that I’m walking the tree recursively calling the FindMyControl method over and over again until I find the control I’m looking for.

Don’t forget the test for null in the if (Ctrl.ID != null && Ctrl.ID.ToLower() == controlID.ToLower()) statement. Of course make sure the test for null comes first.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Search
Contact Us
Use our Contact Us page, or give us a call using the link below