“Cannot save the property settings for this Web Part” error when using SmartPart in SharePoint

I recently deployed a custom user control usingĀ SmartPart on SharePoint 2007, and although everything else seemed to work fine, I came across the following error when trying to edit the properties (in my case, the chrome type and width):

Cannot save the property settings for this Web Part. Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))

I managed to resolve this, thanks to an MSDN forum post, by changing one of my lines of code:

using (SPSite oSiteCollection = SPContext.Current.Site)

to the slightly more long-winded:

using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.ID))

I’m not sure why using SPContext.Current.Site directly (versus creating a new SPSite object) causes this behaviour, but at least it’s a simple fix.

How to check whether a SharePoint user is in a particular group

Here’s a quick function I wrote to check whether a user is a member of a particular SharePoint group:

private bool IsMemberOf(string groupName)
{
    SPUser user = SPContext.Current.Web.CurrentUser;

    try
    {
        if (user.Groups[groupName] != null)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}

The try-catch is required as – somewhat counter-intuitively – SharePoint seems to throw a “Group not found” error if the user is not a member of the group.

How to set SharePoint page title programmatically

I’ve spent some time today trying to figure out how to set the title of a SharePoint page from my own code. As blogger Michael Becker rightly points out, you can’t simply set Page.Title.

The correct solution, as provided by Michael, is illustrated in this example C# code:

// Get a reference to the appropriate Content Placeholder
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) 
                       Page.Master.FindControl("PlaceHolderPageTitle");

// Clear out anything that SharePoint might have put in it already
contentPlaceHolder.Controls.Clear();

// Put your content in
LiteralControl literalControl = new LiteralControl();
literalControl.Text = "Your text goes here";
contentPlaceHolder.Controls.Add(literalControl);

Happily this even works when you “cheat” by hosting an ASP.NET user control within a SmartPart, as opposed to creating a bona fide Web Part.