This article shows how to add a user in a SharePoint 2010 site programmatically. Here we have a Group already defined in that site, we select the user name from a dropdown selection to add a user to the selected group. This shows the details of a generic function in which you pass the group name and user name, then the function will add the user into the group.
<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>
The following is the code to show how to add a user to a 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);
}