SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i want to add a user to a spgroup with specified roles can any one help to write the code in visual webpart?

thanks Naveen

share|improve this question

You may need to customized it for your requirements. Sorry I left out the 2nd half where SPGroup plays role. (run under using or add dispose, add try n catch as well)

//Open Site
SPSite spSite = new SPSite(strSiteURL);
SPWeb spWeb = spSite.OpenWeb();

if(spUser == null)
    spUser = CreateUser(strLoginName, strEMail, strName, strNotes, strSiteURL);

//Open group
SPGroup spGroup = spWeb.SiteGroups[strGroup];

//Add and update group with new user
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");

private SPUser CreateUser(string strLoginName, string strEMail, 
    string strName, string strNotes, string strSiteURL)
    SPUser spReturn = null;
    SPSite spSite = null;
    SPWeb spWeb = null;

        //Open the SharePoint site

        spSite     = new SPSite(strSiteURL);
        spWeb     = spSite.OpenWeb();

        //Assign role and add user to site

        SPRoleAssignment spRoleAssignment = 
            new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);
        //Using Contribute, might need high access

        SPRoleDefinition spSPRoleDefinition = 


        //Update site

        spReturn = spWeb.AllUsers[strLoginName];

    return spReturn;
share|improve this answer
You should really include using statements in code example you provided. By doing so code will be more readable. And creating another SPSite/SPWeb objects just to add new user looks like overkill. Keep your example simple. – Vedran Rasol Oct 3 '11 at 15:31

What type of roles are you refering to? SPRoles? ASP.NET roles?

SPGroup.AddUser method

share|improve this answer
I want to add as sproles... – Naveen Oct 4 '11 at 4:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.