theNoob
theNoob

Reputation: 181

How to set a group of users in to a sharepoint "persons or group" column - Programmatically

I want to add a set of users to the person and group column in my sharepoint list How do I add it to the list?

This is what I did:

            SPUserCollection users;
            SPList oSpList = oSPWeb.Lists["VProducts"];
            SPListItem item = oSpList.GetItemById(productId);
            users = (SPUserCollection)item["Followers"];

            users.Add(curUser.LoginName, email, curUser.Name, curUser.Notes);

I don't know if the way I retrieve the set of users from the list is correct and the way to add a user and set it back. The last line gives an null pointer exception. I tried using SPGroup but couldnt figure out a way to get it done.

Upvotes: 1

Views: 2784

Answers (1)

Petr Novák
Petr Novák

Reputation: 431

This should work for you:

SPList oSpList = oSPWeb.Lists["VProducts"];
SPListItem item = oSpList.GetItemById(productId);

SPFieldUserValueCollection users = GetFieldUserValueCollection(oSPWeb, item["Followers"])
users.Add(new SPFieldUserValue(oSPWeb, curUser.ID, curUser.LoginName))

item["Followers"] = users;
item.Update();

The GetFieldUserValueCollection method code is below:

private SPFieldUserValueCollection GetFieldUserValueCollection(SPWeb web, object userField)
{            
    //If userField object is null return empty collection
    if (userField == null)
        return new SPFieldUserValueCollection();                   

    return new SPFieldUserValueCollection(web, userField.ToString());
}

Upvotes: 1

Related Questions