Home > SharePoint 2010 > Get Parent SPWeb for a particular level from a subsite

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:
http://www.abc.com/def/ghi/jkl/xyz
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 ("http://www.abc.com/def/ghi/jkl/xyz");

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

Advertisements
Categories: SharePoint 2010
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: