Add users to SharePoint group programmatically

In this article how we can add a user in SharePoint 2010 site programmatically. Also you can check out some posts on:

Read some SharePoint tutorials

SharePoint Designer 2016 Download and Updates

Dropdown list with multiple selection option in SharePoint 2010

SP.UI.ModalDialog.showModalDialog() do not work in SharePoint 2013

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

Programmatically add or assign user to User Group in SharePoint
Programmatically add or assign user to User Group in SharePoint

Below is the full code:



<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 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);
}


You May Also like the Following SharePoint Online Tutorials:

About 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.

View all posts by Sagar Pardeshi →

Leave a Reply