Thursday, November 10, 2011

Programmatically find SharePoint 2010 Web Control references in your code-behind files


Programmatically find SharePoint 2010 Web control references in the code-behind files like .aspx.cs for Page Layouts or Custom Application Pages and .ascx.cs for User Controls and Visual Webparts.

I tried to get a handle to the RichHtmlField control in SharePoint using the standard .NET way like this:
Control ctrl = this.FindControl("controlID") as Control;

Sadly it did not work.

So had to write a generic FindControlRecursive methods to get a reference to any SharePoint Web Control used in Page Layouts, Application Pages, Visual WebParts, User Controls etc. See the function call and the generic functions. Copy the code and use it to your advantage.

Function call:

RichHtmlField pageContent = FindControlRecursive(this.Page, "pageContent") as RichHtmlField;

Generic Methods:

         private static Control FindControlRecursive(Page page, string controlID)
        {
            foreach (Control controlToSearch in page.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);

                if (controlToReturn != null)
                {
                    return controlToReturn;
                }
            }

            return null;
        }
     

        private static Control FindControlRecursive(Control rootControl, string controlID)
        {
            if (String.Equals(rootControl.ID, controlID))
            {
                return rootControl;
            }

            foreach (Control controlToSearch in rootControl.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);

                if (controlToReturn != null)
                {
                    return controlToReturn;
                }
            }

            return null;
        }

Hope it helps. Happy Programming.