SharePoint – Setting users or groups for a membership webpart through code

This is a rather simple thing… well once you have cracked it :).


There are two properties which need to be set:

And that is it. To find the “main” associated groups to your site you could use these properties:

using (SPSite site = new SPSite(wsSite.ID))
using (SPWeb web2 = site.OpenWeb(wsSite.RootWeb.ID))
var pubWeb = PublishingWeb.GetPublishingWeb(web2);

using (var wpm = pubWeb.DefaultPage.GetLimitedWebPartManager(PersonalizationScope.Shared))
// Search for the right webpart(you could use LINQ instead of a foreach)
int memberShipWebPartsCount = 0;
for (int x = wpm.WebParts.Count - 1; x >= 0; x--)
var membersWebPart = wpm.WebParts[x] as Microsoft.SharePoint.WebPartPages.MembersWebPart;
if (membersWebPart != null)

// There are only two members webparts which are needed to be processed, at the moment
if (memberShipWebPartsCount < 2)
if (memberShipWebPartsCount == 0)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedOwnerGroup.ID;
else if (memberShipWebPartsCount == 1)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedMemberGroup.ID;

membersWebPart.DisplayType = Microsoft.SharePoint.WebPartPages.MembersWebPartDisplayType.GroupMembership;

if (pubWeb.DefaultPage.CheckOutType != SPFile.SPCheckOutType.None)

if (pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableVersioning && pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableMinorVersions)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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