Archive for June, 2010

Get Parent SPWeb for a particular level from a subsite

I came accross this question recently and decided to blog it with my solution. Here is the scenario

Requirement :

I have a nested subsite called xyz as follows:
How can I get the SPWeb object of "def" from within "xyz" programmatically?
I do not want to use the static way of doing 3 ParentWeb’s instead I was wondering if there is an API method or way that would allow me to get the reference to "def" from within "xyz"

Solution :
We have done the similar approach in a project but by introducing the levels. You can decide the levels for your site hirarchy. In above case you may say you want to get parent SPWEB object of level 2. so you want to do it this way by having a function, You may run into such scenario where you want to get SPWeb object for a level to show the menu etc etc.

your levels are like following for the URL mentioned above.
rootweb = Level 1, def = Level 2, GHI = Level 3, JKL = Level 4, XYZ= Level 5 

public SPWeb getSPWebFromCurrentWeb(SPWeb AnyWeb, int iLevel)


    SPWeb countParent = currentWeb.ParentWeb;
    int iCount=0;    //You need to count how many webs you have.
     while (countParent != null)
          countParent = countParent.ParentWeb;
           iCount=iCount + 1;

     //Return the SPWeb
     SPWeb webParent = AnyWeb.ParentWeb;
     for(int i=iLevel,i<iCount, i++)
           if (webParent != nul)
                   webParent = webParent.ParentWeb;


return webParent;

} //End of Function

and you can call the function this way

SPSite site=new SPSite ("");

SPWeb currentWeb=site.OpenWeb();
SPWeb parentWeb=getSPWebFromCurrentWeb(currentWeb, 2);

Categories: SharePoint 2010