How do i add a user to a group using SharePoint Object Model.
The following function will help you to achieve this...
1. Get the loginname of the user and pass it to the following function
2. the following code adds the user to the Sharepoint Group called MYSite_MyGroup1.
public void AddUser(strloginName)
{
if (!string.IsNullOrEmpty(strloginName))
{ //Gets the Collection of Site Groups
SPGroupCollection objSPSiteGroups = objSPWeb.SiteGroups;
string strCustomGroupName = "MYSite_MyGroup1";
if (objSPSiteGroups != null && !string.IsNullOrEmpty(strloginName))
{
// Adds the new user to the MYSite_MyGroup1 group
objSPgpUserGroup = objSPWeb.SiteGroups[strCustomGroupName];
// Make sure that the user is added to site . the following built in method makes sure it is added to the site
objnewUser = objSPWeb.EnsureUser(strloginName);
//Add the user to group
objSPgpUserGroup.AddUser(objnewUser);
objSPgpUserGroup.Update();
}
}
}
And thats it...
No comments:
Post a Comment