Pages

Wednesday, June 17, 2009

How to add/update SharePoint person/group field from Object model

While adding/updating the person/group field, we need to take care, because it’s required to be in specific format like value must be ID;#Name when assigning value.

Example code:
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
try
{

web.AllowUnsafeUpdates = true;
string loginName = "domainname\\username";
SPUser theUser = web.SiteUsers[loginName];
SPList theList = (SPList)web.Lists["firstcustomlist"];
SPListItem theItem = theList.GetItemById(1);

theItem["usercol"] = theUser.ID.ToString() + ";#" + theUser.Name;
theItem.Update();
theList.Update();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
}

2 comments:

  1. How do you add multiple people to the field? Is there a separator that needs to be used?

    ReplyDelete
  2. Hi

    SPUser object, it gives the ID (SPUser.ID.ToString() and SPUser.LoginName.ToString() ) and then use simple string building to get the string in the right format for the ‘Person or Group’ field.

    Please review the following code in which it accepts a semi-colon delimited list of aliases (i.e. domain\user;domain\user;domain\user) and then adds them to a ‘Person or Group’ field called ‘MyPersonField’ in a list.


    string sAliases = "domain\user;domain\user;domain\user";

    string UserNames = "";

    using (SPSite site = new SPSite("URLof the site"))
    {
    site.AllowUnsafeUpdates = true;
    using (SPWeb web = site.RootWeb)
    {
    web.AllowUnsafeUpdates = true;
    string[] aAliases = sAliases.Split(';');
    foreach (string sAlias in aAliases)
    {
    SPUser user = web.EnsureUser(sAlias);
    UserNames += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
    }
    web.Update();
    }
    }

    if (UserNames.EndsWith(";#"))
    {
    UserNames = UserNames.Substring(0, UserNames.Length - 2);
    }


    SPList l = web.Lists[""];
    SPListItem li= l.Items.Add();
    li["Title"] = UserNames ;
    li["MyPerson"] = UserNames ;
    li.Update();


    Hope this Helps!!!
    Disha Shah

    ReplyDelete