Many times we create custom lists in SharePoint and perform CRUD operations. In this post, we will look at how to match the data from the people and the groups field having multiple entries, using Visual Web part.
Using the code given below, we fetched the data from the list with the multiple values of type user.
We have a custom list with the field Person having data type People and groups.
Steps
- Create an empty project -> add Visual Web part.
- Open .ascx file add people picker field and a button, as shown below.
- <SharePoint:ClientPeoplePicker ID=”persons” runat=”server” AllowMultipleEntities=”true” />
- <asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="btnSubmit_Click" />
- Open .cs file and add the code given below.
-
- protected void btnSubmit_Click(object sender, EventArgs e) {
- try {
- string strPerson = GetSPUserName(persons);
- using(SPWeb oWeb = SPContext.Current.Site.OpenWeb(sitename)) {
- SPList oList = oWeb.Lists.TryGetList(listname);
- if (oList != null) {
- string sQuery = ””;
- sQuery = “ < Where > < In > < FieldRef Name = ’Person’ / > < Values > ”;
- foreach(string struser in strPerson.Split(‘;’)) {
- sQuery += “ < Value Type = ’User’ > ”+struser + “ < /Value>”;
- }
- sQuery += “ < /Values></In > ”;
- sQuery += “ < /Where>”;
- string sViewFields = “ < FieldRef Name = ’ID’ / > < FieldRef Name = ’Title’ / > ”;
- SPQuery objSPQuery = new SPQuery();
- objSPQuery.Query = sQuery;
- objSPQuery.ViewFields = sViewFields;
-
- SPListItemCollection objListItemCollection = oList.GetItems(objSPQuery);
- }
- }
- } catch (Exception err) {}
- }
-
- private string GetSPUserNameCP(ClientPeoplePicker peoplePicker) {
- string names = string.Empty;
- PickerEntity entProfMgr = new PickerEntity();
- foreach(var entity in peoplePicker.ResolvedEntities) {
- entProfMgr = (PickerEntity) entity;
- if (entProfMgr.EntityData[“DisplayName”] != null) names = names + Convert.ToString(entProfMgr.EntityData[“DisplayName”]) + “;”;
- }
- names = string.IsNullOrEmpty(names) ? string.Empty : names.Substring(0, names.LastIndexOf(‘;’));
- return names;
- }
Thanks.