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.

Comments -
  1. Gravatar

    Thank you

  2. Gravatar

    Hi Sudhir,

    Does this problem only occur when you first access the site, of also when you access the site for a second time?
    A user only gets added to the users of a particular web after he or she has accessed the site once, so I can image that can cause problems. You can either not show the webpart on first load, or you can use the EnsureUser function. That would require you to get the username using .Net methods and then use SPWeb.EnsureUser(username) to use code to add a user to the web’s collection of users. After using the EnsureUser function you should be able to retrieve the SPUser object using SPContext.Current.Web.CurrentUser.

    More info on EnsureUser:

    Hope this helps.

  3. Gravatar

    Hi Sudhir,

    Are you using Forms Based Authentication?
    In that case you should be able to use EnsureUser("username") without a domain and an @. Otherwise it depends on the type of authentication you are using.


Comments have been closed on this topic.