SharePoint | Properly parse users from multi user field

Problem:

Value retrieved from a SharePoint multi-user field is:

"44;#Tiago Duarte;#133;#Project ..."


  • User names (starting with #)
  • User ID (which if you remove # you will find a digit)
Using the two assumptions above, you can do a split by ";" and test which values are digits (Int32.TryParse) after removing the '#' sign (replacing "#" by "").

However, do know that there is a way better solution.
SPFieldUserValueCollection will take the web and the field value and properly contain a list of the web's users contained in the provided field.

Solution:


private void ProcessUsers(SPListItem item, string fieldName)
{
  string fieldValue = item[fieldName] as string;
  SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, fieldValue);

  foreach(SPFieldUserValue uv in users)
  {
    SPUser user = uv.User;
    // Process user
  }
}

Thanks to:
http://stackoverflow.com/questions/404024/how-best-to-convert-a-sharepoint-multi-user-field-string-into-an-array-of-spuser

Comments

  1. What about if you aren't running in a context? I.E you are using SP list web services?
    This is not parsing a user string field, it's using objects which you can't do if you're workign with Services.

    ReplyDelete
  2. we'll if we have a list of users and we want to do something for each of them, I call that parsing. I tend to believe that we should take advantage of these strong types instead of messing around with string concatenation and splits. there should be classes for both server side and client side. if there is no alternative (could be the case), I guess we'll have to really master the type formats, specially dates (e.g. 2014-05-01T00:00:00Z) and single (-1;#LABEL|GUID) or multi-value MMS fields (-1;#LABEL1|GUID1 ;# -1#LABEL2|GUID2 ;# -1#LABEL3|GUID3). there are so many apis now that it also depends on what we are using.

    ReplyDelete

Post a Comment

Popular posts from this blog

Mobile development opportunities

Breaking down document locking in SharePoint

Working around X-Frame-Options for iframes