.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Post New Resource Bookmark and Share   

Programmatically how to add /assign user to a User Group in SharePoint

Posted By:Sagar Pardeshi       Posted Date: March 17, 2014    Points: 200    Category:    URL: http://www.dotnetspark.com  

Programmatically how to add /assign user to a User Group in SharePoint
 

Introduction 

In this article how we can add a user in SharePoint 2010 site programmatically. 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



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





     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend