Insert multi user or more than one user in SharePoint list Person or Group field

Objective

In this article, I am going to explain, how to insert multi user or more than one user in Share point list.

About SharePoint list where value would be inserted

  1. There is a list called TestingUser.
  2. There is one column in list called UserTest.
  3. This column is of type Person or Group.
  4. Allow multiple selections are true.
  5. Allow selection is set to People and Group.


TestingUser list looks like below, 

1.gif




How to Insert?

Let us suppose, you need to add more than one user at single time in SharePoint List. Users' values may come from an Active Directory or metadata.  All the users are in a string as comma or semicolon separated value.  Let us suppose users are in below format.

string usercontrolvalue = "dhananjay,arun,anoj,patra,mub";

We need to inert these multiple users in a column of type People or Group in SharePoint list.

Step 1

First we need to split name of all the users from the string. Since in our case users are comma separated so below code will make a string array with users as value at different index.

string[] userarray = usercontrolvalue.Split(',');

Step 2

Now we need to convert users as string to SPFieldUserValue.  Below function is taking user name as string and converting that into SPFieldUserValue. 

_Web variable is denoting current web where List is part of.

public  SPFieldUserValue ConvertLoginName(string userid)
{
    SPUser requireduser = _web.EnsureUser(userid);
    SPFieldUserValue uservalue = new SPFieldUserValue(_web, requireduser.ID,   requireduser.LoginName);
    return uservalue;
}

Step 3

We need to make instance of SPFieldUserValueCollection

SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();

Step 4

For all the user; we need to convert that as SPFieldUserValue then add that them to  SPFieldUserValueCollection  instance

for (int i = 0; i < userarray.Length; i++)
{
    SPFieldUserValue usertoadd = ConvertLoginName(userarray[i]);
    usercollection.Add(usertoadd);
}

Only we need to perform above said task. For your reference entire code as below,

Entire code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;  

namespace TestingMultipleUsre
{
    public partial class _Default : System.Web.UI.Page
    {
        SPWeb _web;
        SPSite _site;
       SPList myList
        protected void Page_Load(object sender, EventArgs e)
        {
            string usercontrolvalue = "dhananjay,arun,anoj,patra,mub";
             _site = new SPSite("http://adfsaccount:2222/");
             _web = _site.OpenWeb();
             myList = _web.Lists["TestingUser"];
             _web.AllowUnsafeUpdates = true ;
             myList = _web.Lists["TestingUser"];
            SPListItem item = myList.Items.Add();
            SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
            string[] userarray = usercontrolvalue.Split(',');
            for (int i = 0; i < userarray.Length; i++)
            {
                SPFieldUserValue usertoadd = ConvertLoginName(userarray[i]);
                usercollection.Add(usertoadd);
            }
            item["UserTest"] = usercollection;
            item.Update();
        }
        public  SPFieldUserValue ConvertLoginName(string userid)
        {
            SPUser requireduser = _web.EnsureUser(userid);
            SPFieldUserValue uservalue = new SPFieldUserValue(_web, requireduser.ID, requireduser.LoginName);
            return uservalue;
        }
    }
}

Note
:
Make sure all the users; you are adding are user of the Sharepoint.

Output

While running output would be as below

Conclusion

In this article, I have explained how to insert more than one user in SharePoint list. Thanks for reading.

resource:http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/multiple-user-insertion-in-sharepoint-list/

resource:http://blogs.msdn.com/b/uksharepoint/archive/2009/02/17/quick-tip-using-the-sharepoint-person-or-group-field-in-code-part-1.aspx

(Do not recommended)

One of the coolest types of site column (or field) in SharePoint is the ‘Person or Group’ field type. This allows you to select people from the GAL using a nice little picker control. When users are selected, you benefit from all of the presence capabilities of SharePoint as shown in this screen shot:

I recently had to programmatically add users to one of these ‘person or group’ fields where I only had the Login Name (domain\user) of the user I was adding as an input. It took me a while to work out how to populate a ‘Person or Group’ field from code so I thought I’d share my findings. It is worth noting that my esteemed co-workers Nigel Bridport and Pete Mellish both helped with figuring out the right format for this.

In order to populate these fields, you need a very specific combination of the User ID (see below for how to get this), their full Login Name (domain\user) and some magic characters (;#). The actual formula is as follows

<UserID>;#<UserLoginName>

for example

10;#europe\mkearn

In actual fact, I found that if you are only entering one person, you only need the User ID, but I think it is best to add the alias if you can. If you wish to add multiple people it is the same formula but the different people are separated by ;# as shown below

<UserID1>;#<UserLoginName1>;#<UserID2>;#<UserLoginName2>;#<UserID3>;#<UserLoginName3>

for example

10;#europe\mkearn;#3;#europe\ashleyy;#12europe\johnc

Word of warning ….If you wish to add your ‘Multiple Person or Group’ field via a Feature or Site Definition, there are some key things you need to know about Multiple User fields. See George Bonney’s great article which give you all of the details on how to do this.

So now we have the right formula, how do we actually use it?

The UserID relates to the ID of the user within the site collection. This is fine but the chances are that not all users are members of the site collection. To address this, the SharePoint OM has a handy little method called SPWeb.EnsureUser() which accepts a Login Name of a user as a string and first checks if the user exists in the site collection, if it does not then it adds the user and returns an SPUser object. Please be aware that you may need to set SPWeb.AllowUnsafeUpdates = True for this to work.

From the SPUser object it is very simple to get the ID (SPUser.ID.ToString() and SPUser.LoginName.ToString() ) and then use simple string building to get the string in the right format for the ‘Person or Group’ field.

The following code is a simple example of a Console Application which accepts a semi-colon delimited list of aliases (i.e. domain\user;domain\user;domain\user) and then adds them to a ‘Person or Group’ field called ‘MyPersonField’ in a list.

You can add this to the Main method of a Console Application and so long as you add the necessary references to SharePoint dlls (and the right using statements) it will work if you execute it on a SharePoint server (be sure to change the values of site, list and the name of the ‘MyPerson’ field to match your setup).

Console.WriteLine("Enter a ; delimited list of domain\alias that need to be added:");
string sAliases = Console.ReadLine(); //captures whatever the user entered
string sValueToAddToFieldInSP = ""; //used to build the full string needed for the person field

string sAllContacts = "";

using (SPSite site = new SPSite(“http://sites/site/yoursite”))
{
    site.AllowUnsafeUpdates = true;
    using (SPWeb web = site.RootWeb)
    {
        web.AllowUnsafeUpdates = true;
        string[] aAliases = sAliases.Split(';');
        foreach (string sAlias in aAliases)
        {
            SPUser user = web.EnsureUser(sAlias);
            sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
        }
        web.Update();
    }
}

if (sAllContacts.EndsWith(";#"))
{
    sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2);
}

//add the list item
SPList l = web.Lists["<name of your list>"];
SPListItem li= l.Items.Add();
li["Title"] = sAllContacts ;
li["MyPerson"] = sAllContacts ;
li.Update();
Console.WriteLine("Done");

Using the InfoPath Contact Selector Control

One of the main places where you might use the technique described in this article is in an InfoPath where you wish to use the users selected in a Contact Selector control and promote them to SharePoint as a ‘Person or Group’. Unfortunately, this is not quite as simple as it should be because InfoPath does not natively understand the ‘Person or Group’ field type in SharePoint so you cannot directly promote it via property promotion.

The explanation of how you might do this in InfoPath is too lengthy for this article so watch this space for a follow-up coming soon!!

That is the end of the article, I hope you found it useful.

 

原文地址:https://www.cnblogs.com/ilawrence/p/2783681.html