Monday, 11 February 2013

SharePoint Form Control People Picker Has Problems Resolving User Value

This latest issue is exactly what it says on the tin :) You have a People Picker control which is used to story a value that corresponds to an SPFieldUserValue in a SharePoint list object. Because there is no instant conversion between the value in the People Picker you perform a conversion:

string userValue = userCtrl.Value.ToString();
int pos = userValue.IndexOf("#");
userValue = userValue.Substring(pos + 1);

(there may well be more elegant ways to get the value out of the People Picker, by all means go out and find them.)

This should extract the part of the uservalue that reads "DOMAIN\username_s" which is what we need to create the SPUser object

SPUser user =   web.EnsureUser(userValue);

I run this for user X and it works perfectly. All good. Then another tester notes that when she enters user Y and clicks Submit, the page doesn't update properly. After a bit of fiddling I discover that in the case of this particular user, the Value property on the People Picker control returns a number, that is, the SharePoint user ID. It is not possible to use this as a parameter for the EnsureUser method, so we are in error city.

So naturally I wondered, why is it behaving for user X and not for user Y. Did a bit of googling and came up with this. It appears to have something to do with the user list in SharePoint. So I went into that user, clicked the Edit User and saved without changing anything. Reran the code. Still had the same problem.

This is how I fixed it in the code - but I still don't know why it didn't work for that user but did for every single other user I tried. So any suggestions on that front welcome.

  int SPId;
 SPUser managerUser = null;
 if (Int32.TryParse(managerValue.Trim(), out SPId) == true)
        managerUser = web.SiteUsers.GetByID(SPId);
        managerUser = web.EnsureUser(managerValue);

No comments:

Post a Comment