Saturday 12 October 2013

How to create sharepoint people picker textbox using asp.net :

To create people picker in Sharepoint use people editor tag in .ascx page as shown below :

<SharePoint:PeopleEditor runat="server" ID="peopleEditorID"  PlaceButtonsUnderEntityEditor="false"  SelectionSet="User" />

The above code works well for single user/people selector at a time . To select multiple users/peoples at a time you have to add "MultipleUser=true" attribute to the above tag.
Now the people editor is able to select the people and display in textbox. But in order to reflect/store this into the Sharepoint List follow the below code.

Code to save people editor selected user into Sharepoint List people picker field :(code-behind code)


         string siteUrl = SPContext.Current.Web.Url;
         using (SPSite spsite = new SPSite(siteUrl))
         {
              using (SPWeb spWeb = spsite.OpenWeb())
                {
                    SPList spList = spWeb.Lists["YourListName"];
                    SPListItem spListItem = spList.Items.Add();
                        try
                        {
                            string name= GetUserName(peopleEditorID);
                            if (name != null)
                            spListItem["PeoplePickerFeildName"] = spWeb.EnsureUser(name);
                            spListItem.Update();
                        }
                        catch (Exception e)
                        {
                        }
                 }
        }

        public string GetUserName(PeopleEditor editorName)
        {
            if (editorName.ResolvedEntities.Count <= 0)
                return null;
            using (SPSite spsite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spsite.OpenWeb())
                {
                    var picker = spWeb.EnsureUser(editorName.CommaSeparatedAccounts);
                    String userName = picker.Name;
                    return userName;
                }
            }
        }



No comments:

Post a Comment

Total Pageviews