I've got the following code that works well on most pages in SharePoint 2010; but it blows up on Site Actions > Site Settings > Manage site features with a NullReferenceException on the GetRootTitle() function. This is called from a custom master page (copy of v4.master):
protected string title = string.Empty;
protected override void OnLoad(EventArgs e)
{
// To ensure page behaves correctly, must call base.OnLoad(e).
base.OnLoad(e);
GetRootTitle();
}
private void GetRootTitle()
{
SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
IterateThroughParentsAndStoreInfo(web);
// Set a label's value to the title.
sectionTitle.Text = title;
web.Dispose();
site.Dispose();
}
private void IterateThroughParentsAndStoreInfo(SPWeb web)
{
// Do your code for the 'web' variable here.
if (web.ParentWeb != null)
{
title = web.Title;
using (SPWeb parentweb = web.ParentWeb)
{
IterateThroughParentsAndStoreInfo(parentweb);
}
}
}
Here's the error the http://myserver/mysite/_layouts/ManageFeatures.aspx page throws:
10/27/2011 13:59:46.92 w3wp.exe (0x26E8) 0x2334 SharePoint Foundation Runtime tkau Unexpected System.NullReferenceException: Object reference not set to an instance of an object. at ASP._8cc5acc7_8688_48f0_94fc_2a6d6124a691__164880475.GetRootTitle() at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) aae55609-5b47-44c4-a883-752ad8cd2aa7
Update: For those wondering about the correct code, here it is (thanks to everyone's help!):
protected override void OnLoad(EventArgs e)
{
// To ensure page behaves correctly, must call base.OnLoad(e).
base.OnLoad(e);
GetRootTitle();
}
private void GetRootTitle()
{
string title = string.Empty;
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
title = IterateThroughParentsAndStoreInfo(web, title);
}
}
title = (title.Length >0) ? title : SPContext.Current.Site.RootWeb.Title;
sectionTitle.Text = title; // Set a label's value to the title.
}
private string IterateThroughParentsAndStoreInfo(SPWeb web, string title)
{
if (web.ParentWeb != null)
{
title = web.Title;
return IterateThroughParentsAndStoreInfo(web.ParentWeb, title);
}
return title;
}
With the using clause, the CLR automatically wraps the code in try/catch/finally statements and will dispose of the objects correctly as well.
<SharePoint:ProjectProperty Property="Title" runat="server" />was in the master page. – Alex C Oct 27 '11 at 15:03