Tuesday, February 26, 2013

Programmatically assign a SharePoint user to a "Person or Group" column in a SharePoint list

Here is some sample code that demonstrates how you can assign a given SharePoint user to a "Person or Group" column or field (in this case, I have a custom "Person or Group" field called "Owner") contained within a SharePoint list:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

...

Guid siteId = new Guid("GuidOfSiteCollection");
Guid webId = new Guid("GuidOfSite");
Guid listId = new Guid("GuidOfList");
string itemTitle = "My Item's Title";
string userName = "Domain//UserName";

using (SPSite site = new SPSite(siteId))
{
    using (SPWeb web = site.OpenWeb(webId))
    {
        // Find all list items that match your search criteria
        SPQuery query = new SPQuery();
        query.Query = string.Format("{0}", itemTitle);
        SPListItemCollection items = web.Lists[listId].GetItems(query);
        // Obtain a reference to SPUser object associated with the specified user
        SPUser user = web.AllUsers[userName];
        // Assign the user to the custom "Owner" field of my SharePoint list items
        web.AllowUnsafeUpdates = true;
        foreach (SPListItem item in items)
        {
            if (user != null)
            {
                item["Owner"] = user;
                item.Update();
            } 
        }
        web.AllowUnsafeUpdates = false;
    }
}
As you can tell, this is a super-simplified version of some actual code that I've got working. Naturally, you will want to organize this code to better suit your needs (as well as add some exception handling), but the purpose of this example is to show you the basics of how it's done. Enjoy!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.