The use of SPContext

When building custom web parts for Windows SharePoint Services V3. You can use the SPContext object to get for instance the site or web from the current context.  But that's not all you can get from SPContext. You can also get the listitem and the webfeatures.

In WSS V2 you would use SPControl.GetContextSite() or SPControl.GetContextWeb() but that's a lot less flexible and it's slower as well.

A couple of different uses of SPContext are shown below:


SPList currentList = SPContext.Current.List;

SPWeb currentSite = SPContext.Current.Web;

SPSite currentSiteCollection = SPContext.Current.Site;

SPWebApplication currentWebApplication = SPContext.Current.Site.WebApplication;


SPListItem item = (SPListItem)SPContext.Current.Item;


SPWeb site = SPContext.Current.Site.OpenWeb(guid);

SPUser user = SPContext.Current.Web.CurrentUser;


SPSiteDataQuery siteQuery = new SPSiteDataQuery();

siteQuery.Query = "<Where><Gt><FieldRef Name=\"ID\" />" +

    "<Value Type = \"Number\">100</Value></Gt></Where>";

siteQuery.ViewFields = "<FieldRef Name=\"Title\"/>";

DataTable queryResults = SPContext.Current.Web.GetSiteData(siteQuery);

queryResults.TableName = "queryTable";


The last example makes use of the SPSiteDataQuery object.  In WSS V3 there are two different query objects. Besides SPSiteDataQuery object there is also the SPQuery object.
The difference between the two is that SPQuery can only be used for queries within a single folder in a single list. SPSiteDataQuery can be used for cross lists and even cross site queries.