Share via


How to programmatically find a control in SharePoint page?

While working on customer issue,I have faced an interesting scenario to find a SharePoint control. I though it’s as easy as in ASP.NET where I have write just one single line to code to find the control in page.

Control myControl = this.FindControl(_ControlID);

But when it comes to SharePoint, I didn't get the control in the same way. Let me show you a snippet of my custom aspx page :-

    1: <asp:TreeView runat="server" id="TreeView1" DataSourceID="siteMapDataSource2" ></asp:TreeView>
    2:  <PublishingNavigation:PortalSiteMapDataSource ID="siteMapDataSource2" Runat="server"
    3:         SiteMapProvider="CombinedNavSiteMapProvider" EnableViewState="true"
    4:         StartFromCurrentNode="true" StartingNodeOffset="0" ShowStartingNode="false"
    5:         TreatStartingNodeAsCurrent="true" TrimNonCurrentTypes="Heading"/>

following is code snippet that helps to find the TreeView control from the page :-

    1: <script runat="server">
    2: TreeView oWPM;    
    3: protected override void OnLoad(EventArgs e)
    4: {
    5:        //base.OnLoad(e);
    6:         foreach (Control c in this.Page.Controls)
    7:         {
    8:  
    9:  
   10:             FindControlsRecursive(c);
   11:         }
   12:  
   13:    }
   14:  
   15:  private void FindControlsRecursive(Control root)
   16:  {
   17:  
   18:                       foreach (Control oControl in root.Controls)
   19:                       {
   20:  
   21:                           if (oControl.GetType().FullName == "System.Web.UI.WebControls.TreeView")
   22:                           {
   23:  
   24:                               this.oWPM = (System.Web.UI.WebControls.TreeView)oControl;
   25:                               this.oWPM.TreeNodeDataBound +=new TreeNodeEventHandler(oWPM_TreeNodeDataBound);
   26:                              
   27:                             
   28:                           }
   29:                           else if (root.HasControls())
   30:                               FindControlsRecursive(oControl);
   31:                       }
   32:  
   33:                   }
   34:  
   35:                   void oWPM_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
   36:                   {
   37:                       SiteMapNode smn = e.Node.DataItem as SiteMapNode;
   38:                       if(smn["Target"] != null)
   39:                       {
   40:                         Response.Write(smn["Target"].ToString());
   41:                       }
   42: }            
   43: </script>