Monday, November 26, 2007

Adding Users to a SharePoint List

Say you have a list and you wish to copy and paste from excel through the Grid-View Function. You will notice two things as it relates to the People and Groups Field.

  1. It will not take users that do not already exist in SharePoint
  2. It will not copy at all if the people and groups has the "Allow Multiple Selections" checkbox checked

Well now that's a bummer.

The following solution is just what I came up with:

What we are going to do is make a new field that will store a semi-comma delimited list and populate the users in there. We are then going to write some quick c# do take the data from that column and populate correctly across to the correct column.

The first function we will write will take in the SPWeb that you wish to do this for as well as the semi-comma delimited list.


//Return properly validated and added users


private SPFieldUserValueCollection UserValidation(SPWeb web, string Users)

{

SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();


string FormatedUsers = string.Empty;


string[] UserArray = Users.Split(';');


foreach (string sUser in UserArray)

{

SPUser user = null;


try

{

user = web.AllUsers[sUser];

}


catch { }


 


if (user == null)

{


try

{

web.AllUsers.Add(sUser, "", sUser, "");

web.Update();

user = web.AllUsers[sUser];

}


catch { }

}


 


if (user != null)

{

userCollection.Add(new SPFieldUserValue(web, user.ID, user.LoginName));

}

}


 


return userCollection;

}

}


 

The second function we will write will be to take the list, and actually update the list based on the previous method.

public
void UpdateMyList()

{


try

{


//Should do something like:


//string TopLevelSite = ConfigurationSettings.AppSettings["Site"];


string TopLevelSite = "http://r2-basemachine:1111";


using (SPSite SPSSite = new SPSite(TopLevelSite))

{


using (SPWeb sPWeb = SPSSite.OpenWeb())

{


string listName = "DatasheetTest";

SPList list = null;


DataTable dt = null;

SPListItemCollection listCol = null;


 

list = sPWeb.Lists[listName];

listCol = list.Items;

dt = listCol.GetDataTable();


 


foreach (DataRow dr in dt.Rows)

{

SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();

userCollection = UserValidation(sPWeb, dr["Multi"].ToString());

SPListItem ListItem = list.GetItemById((int)dr["Id"]);

ListItem["PersonField"] = userCollection;

ListItem.Update();

}

}

}

}


catch (Exception ex)

{


Console.WriteLine("Error: " + ex.ToString());

}

}


 

Happy coding!

No comments: