Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Programmatically create user groups Sharepoint 2010

Programmatically create user groups Sharepoint 2010

Create a group -

//Add the group to the SPWeb web
web.SiteGroups.Add(“Mygroup”, “ikapoor”, “ikapoor”, “My Readers Group”);

//Associate the group with SPWeb
web.AssociatedGroups.Add(web.SiteGroups["Mygroup"]);
web.Update();

//Assignment of the roles to the group.
SPRoleAssignment assignment = new SPRoleAssignment(web.SiteGroups["Mygroup"]);
SPRoleDefinition _role = web.RoleDefinitions["Read"];
assignment.RoleDefinitionBindings.Add(_role );
web.RoleAssignments.Add(assignment);

Adding users to your new group -

SPUser spUser = spWeb.EnsureUser(“domain\ikapoor”);

if (spUser != null)
{
SPGroup spGroup = spWeb.Groups["Mygroup"];

if (spGroup != null)
spGroup.AddUser(spUser);
}

No comments:

Post a Comment