Set or Get value people editor control in SharePoint 2010 with C#


How to get and set the value of a people editor control programatically in SharePoint 2010?

Get People Editor Values
This code demostrate how to get people editor control values and insert a sharepoint list
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["myList"].Items;

SPListItem item = listItems.Add();

item["Title"] = this.txtTitle.Text.ToString();
item["Location"] = this.lblLocations.Text.ToString();
item["EventDate"] = txtStart.SelectedDate ;

string[] UsersSeperated = pplEditor.CommaSeparatedAccounts.Split(',');
SPFieldUserValueCollection UserCollection = newSPFieldUserValueCollection();
foreach (string UserSeperated in UsersSeperated)
   {
    mySite.EnsureUser(UserSeperated);
    SPUser User = mySite.SiteUsers[UserSeperated];
    SPFieldUserValue UserName = new SPFieldUserValue(mySite, User.ID, User.LoginName);
    UserCollection.Add(UserName);
   }
item["people"] = UserCollection;
item.Update();
Set People Editor values from Sharepoint List
This code demostrate how to set people editor control values from  a sharepoint list
SPSite site = SPContext.Current.Site;
SPWeb myweb = site.OpenWeb();
SPList mylist = myweb.Lists["MyList"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='ID'/>" +
              "<Value Type='Text'>" + e.Value.ToString() + "</Value></Eq></Where>";

SPListItemCollection items = mylist.GetItems(query);
  foreach (SPListItem item in items)
    {

     try
      {

        this.txtTitle.Text = item["Title"].ToString();
        this.txtStart.SelectedDate =Convert.ToDateTime(item["EventDate"].ToString());
       }
        catch (Exception ex)
       {
         Response.Write(ex.Message.ToString());
       }


ArrayList _arrayList = new ArrayList();
SPFieldUserValueCollection users = item["People"asSPFieldUserValueCollection;
  if (users != null)
     {
       foreach (SPFieldUserValue user in users)
         {

          PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
          _pickerEntity.Key = user.User.LoginName;
          _pickerEntity.IsResolved = true;
          _arrayList.Add(_pickerEntity);
          }
        pplEditor.UpdateEntities(_arrayList);

      }
}  

Comments

Popular posts from this blog

IRM and the Object Model

This content database has a schema version which is not supported in this farm

Activate and Deactivate Feature through PowerShell