Using SPContext Class

SPContext class is used to return context information about the current Web application, site collection, site, list, or a list item.


SPList myCurrentList = SPContext.Current.List;
SPWeb myWeb = SPContext.Current.Web;
SPSite mySite = SPContext.Current.Site;
SPWebApplication myCurrentWebApp = SPContext.Current.Site.WebApplication;

To return the top-level web site of the current site collection:
SPWeb myTopLevelSite = SPContext.Current.Site.RootWeb;

To return the current list item:
SPListItem myCurrentItem = (SPListItem)SPContext.Current.Item;

Opening a web in the current site collection and  returning the current user:
using(SPWeb myWeb = SPContext.Current.Site.OpenWeb(GUID Web))
{
    SPUser currentUser = SPContext.Current.Web.CurrentUser;
}

Using SPContext you can also obtain a reference to any web other than the current one. The following code returns the context of any specified site:
SPWeb myWeb = SPContext.Current.Site.AllWebs["AnyOtherSite"];

Hope this helps–
Advertisements
  1. December 12, 2009 at 2:09 pm

    Quick tip, you can get the current context SPListItem without the cast: SPContext.Current.ListItem will return it.

  1. December 4, 2009 at 12:26 am
  2. January 7, 2010 at 5:38 am

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: