Tuesday, September 04, 2012

Adding SPUser programmatically

This few lines of code will be helpful for adding the SharePoint User or SharePoint Group through code. The string value for user id was given in excel format.My workaround was parsing the string in to token and identifying the user's windows log in id. Then inserting this value into people picker and updating the respective item. I have only one user to be added.If you have collection of users then you need to split the strings in comma delimiter and use the SPFieldUserValueCollection class.
 using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser userObj = SPContext.Current.Web.EnsureUser("Murugesan");
                    SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, userObj.LoginName);
                    SPList list = web.Lists["Project"];
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Project-2";
                    item["Manager"] = userValue;
                    item.Update();
                }
            }