Add users to SharePoint group programmatically

Here we have a SharePoint Group already define in that site, we select a user name from dropdown selection add a user on the selected group. This going to detail about a generic function in which you pass group name and user name, then the function will add a user into the group.

We will also see how to add a user to a SharePoint group using SharePoint web service.

Add users to SharePoint group programmatically

Below is the full code to add users to SharePoint group programmatically.

<div class="announcements_detail">
<h2>
Add User To Group</h2>
<div class="rows firstRow">
<div class="col1″>
User Name:</div>
<div class="col2 title">
<div class="inner_col2″>
<div class="user_detail">
<SharePoint:PeopleEditor ID="PplEdtor" runat="server" AllowEmpty="true" MultiSelect="false" SelectionSet="User" ValidatorEnabled="true" />
</div>
</div>
</div>
<div class="clr">
</div>
</div>
<div class="rows">
<div class="col1″>
Groups:</div>
<div class="col2″>
<div class="inner_col2″>
<asp:DropDownList ID="ddlGroups" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqGroups" runat="server" ErrorMessage="Please select Group" ControlToValidate="ddlGroups" InitialValue=""></asp:RequiredFieldValidator>
</div>
</div>
<div class="clr">
</div>
</div>
<div class="rows noBorder">
<div class="col1″>
</div>
<div class="col2 noBg">
<div class="inner_col2″>
<asp:Button ID="bntAddUserToGrp" runat="server" Text="Add User" class="green_gradient_bg"
OnClick="btnAddUserToGrp_Click"></asp:Button></div>
</div>
<div class="clr">
</div>
</div>
<div>
<input class="close_btn" id="btnClose" onclick="javascript:window.close();" type="button" />
</div>
</div>

Below is the code to show to add a user in SharePoint group:

protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
BindGroupsWithDropDownList();
}
}
catch (Exception ex)
{
ShowError("Page_Load: " + ex.Message);
return;
}
}
private void BindGroupsWithDropDownList()
{
try
{
ddlGroups.Items.Clear();
string[] strGroupArr = { "ParticipantGroupName", "MentorGroupName", "SponsorGroupName", "BusinessGroupName" };
foreach (string strGroupType in strGroupArr)
{
ddlGroups.Items.Add(strGroupType);
}
}
catch (Exception ex)
{
ShowError("BindGroupData: " + ex.Message);
}
}
protected void btnAddUserToGrp_Click(object sender, EventArgs e)
{
bool Flag = false;
string strMsg = string.Empty;
try
{
if (PplEdtor.IsValid)
{
string strUsers = GetMembersFromPeoplePicker(PplEdtor);
string strParticipant = SPContext.Current.Web.AllUsers[strUsers].ID + ";#" + strUsers;
string strGroupName = ddlGroups.SelectedItem.ToString().Trim();
string strGrouptyp = ddlGroups.SelectedValue.ToString().Trim();
if (!string.IsNullOrEmpty(strUsers) && !string.IsNullOrEmpty(strGroupName) && !string.IsNullOrEmpty(strGrouptyp))
{
string strSiteUrl = SPContext.Current.Web.Url;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oAdminSite = new SPSite(strSiteUrl))
{
using (SPWeb oAdminWeb = oAdminSite.OpenWeb())
{
if (AddUserToGroup(oAdminWeb, strUsers, strGroupName))
{
Flag = true;
}
else
{
strMsg = "User NOT added to group";
}
}
}
});
strMsg = "User added to group successfully";
}
else
{
strMsg = "Parameters Missing, to add a user!!!";
}
}
else
{
strMsg = "Please enter valid User Name";
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "starScript", "showMessage(‘" + strMsg + "‘);", true);
}
catch (Exception ex)
{
ShowError("btnAddUserToGrp_Click: " + ex.Message);
return;
}
}
public bool AddUserToGroup(SPWeb oWeb, string strUserNameToAdd, string strGroupName)
{
try
{
bool Flag = false;
oWeb.AllowUnsafeUpdates = true;
SPUser spUser = oWeb.EnsureUser(strUserNameToAdd);
if (spUser != null)
{
SPGroup spGroup = oWeb.Groups[strGroupName];
if (spGroup != null)
spGroup.AddUser(spUser);
}
oWeb.Update();
Flag = true;
oWeb.AllowUnsafeUpdates = false;
return Flag;
}
catch (Exception ex)
{
oWeb.AllowUnsafeUpdates = false;
return false;
}
}

private string GetMembersFromPeoplePicker(PeopleEditor oPeopleEditor)
{
try
{
string strLoginNames = string.Empty;
foreach (PickerEntity oUser in oPeopleEditor.Entities)
{
if (oUser.IsResolved)
strLoginNames += (string.IsNullOrEmpty(strLoginNames)) ? oUser.Key : ";" + oUser.Key;
}
return strLoginNames;
}

catch (Exception ex)
{
ShowError("GetMembersFromPeoplePicker: " + ex.Message);
return string.Empty;
}
}

private void ShowError(string strMsg)
{
Response.Write("<br />" + strMsg);
}

Add user to SharePoint group using SharePoint web service

To work with SharePoint web service we need to give the web service reference into SharePoint solution. To add a user to a security group we need to give reference to the UserGroup.asmx web service.

Here we give the reference like below: http:///_vti_bin/UserGroup.asmx

Example: http://bsahoo3:18649/_vti_bin/UserGroup.asmx

Once we give reference we can use the AddGroup method to add a group to SharePoint.

Here the AddUserToGroup method takes 5 parameters like below:

public void AddUserToGroup(string groupName, string userName, string userLoginName, string userEmail, string userNotes)

Below is the full code to add a user to the SharePoint group using SharePoint web service.

try
        {
            UserGroup userGroup = new UserGroup();
            userGroup.Url = "http://bsahoo3:18649/_vti_bin/UserGroup.asmx";
            userGroup.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            userGroup.AddUserToGroup("Viewers", "Sahoo, Bijaya Kumar", "ASIAPACIFIC\\SAHOOBIJ", "bijaya-kumar.sahoo@hp.com", "User Added");
        }
        catch (Exception ex)
        {
        }

Once you will execute the code, the SharePoint user will be added to the SharePoint group, you can see below:

Add user to SharePoint group using SharePoint web service
Add user to SharePoint group using SharePoint web service

You may like following SharePoint JSOM tutorials:

This SharePoint tutorial explains, how to add users to SharePoint group programmatically using the SharePoint server object model code.

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Sagar Pardeshi

I am Developer working on Microsoft Technologies for the past 6+years. I am very much passionate about programming and my core skills are SharePoint, ASP.NET & C#,Jquery,Javascript,REST. I am running this blog to share my experience & learning with the community I am an MCP, MCTS .NET & Sharepoint 2010, MCPD Sharepoint 2010, and MCSD HTML 5,Sharepoint 2013 Core Solutions. I am currently working on Sharepoint 2010, MOSS 2007, Sharepoint 2013,Sharepoint 2013 App Dev, C#, ASP.NET, and SQL Server 2008.

>