Tuesday, June 27, 2006

Sharepoint 2007 - User Or Group Column programatic access

You may have read about this new exciting column available now in sharepoint lists. This column allows users to select from a directory of users by searching. This is a great feature, and today I had to find how to fill that field programatically.

It turns out that the field is (internaly) a look up field - which means it expects a number as an input.

You cant do :

  1. item["Assigned To"] = "administrator";
  2. item["Assigned To"] = "administrator@demo.com";
  3. item["Assigned To"] = "demo\\administrator";

Instead, you have to specify the user ID from the user's list:

item["Assigned To"] = 1;

But how to tell what ID does a user have? The only way I know of is using the "Users" property of the SPWeb object. Lets say you want to assign the field to ishai@demo.com (you only know the email). you can use the following code:
item["Assigned To"] = item.ParentList.ParentWeb.Users.GetByEmail("ishai@demo.com").ID;

If you know the domain name instead of the email, you can use the Users.GetCollection function and pass the domain name as a string array, then get the ID of the first item in the results:
string [] domainName = new string[1];
domainName[0] = "demo\\ishai";

Liked it? Please kick me! kick it on SharePointKicks.com


Tony said...

Thanks for the tip.

How would you save multiple entries to the field/column from the people picker assuming the picker allows multiple selections?

I tried to separate the ids with ";", but it does not work.

Thanks again.

Geert said...

use something like:

string[] names = new string[] { "domain\\eric", "domain\\john" };

pass the names as your userlist.