IN Query In CAML

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
  1. Create an empty project -> add Visual Web part.
  2. Open .ascx file add people picker field and a button, as shown below.
    1. <SharePoint:ClientPeoplePicker ID=”persons” runat=”server” AllowMultipleEntities=”true” />  
    2. <asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="btnSubmit_Click" />  
  3. Open .cs file and add the code given below.
  1. // below code will return the collection where Person column contains the data of people picker field  
  2. protected void btnSubmit_Click(object sender, EventArgs e) {  
  3.     try {  
  4.         string strPerson = GetSPUserName(persons);  
  5.         using(SPWeb oWeb = SPContext.Current.Site.OpenWeb(sitename)) {  
  6.             SPList oList = oWeb.Lists.TryGetList(listname);  
  7.             if (oList != null) {  
  8.                 string sQuery = ””;  
  9.                 sQuery = “ < Where > < In > < FieldRef Name = ’Person’ / > < Values > ”;  
  10.                 foreach(string struser in strPerson.Split(‘;’)) {  
  11.                     sQuery += “ < Value Type = ’User’ > ”+struser + “ < /Value>”;  
  12.                 }  
  13.                 sQuery += “ < /Values></In > ”;  
  14.                 sQuery += “ < /Where>”;  
  15.                 string sViewFields = “ < FieldRef Name = ’ID’ / > < FieldRef Name = ’Title’ / > ”;  
  16.                 SPQuery objSPQuery = new SPQuery();  
  17.                 objSPQuery.Query = sQuery;  
  18.                 objSPQuery.ViewFields = sViewFields;  
  19.                 //objListItemCollection will return the collection which matches the data entered in people picker field  
  20.                 SPListItemCollection objListItemCollection = oList.GetItems(objSPQuery);  
  21.             }  
  22.         }  
  23.     } catch (Exception err) {}  
  24. }  
  25. // Below function will return all the persons in people picker.  
  26. private string GetSPUserNameCP(ClientPeoplePicker peoplePicker) {  
  27.     string names = string.Empty;  
  28.     PickerEntity entProfMgr = new PickerEntity();  
  29.     foreach(var entity in peoplePicker.ResolvedEntities) {  
  30.         entProfMgr = (PickerEntity) entity;  
  31.         if (entProfMgr.EntityData[“DisplayName”] != null) names = names + Convert.ToString(entProfMgr.EntityData[“DisplayName”]) + “;”;  
  32.     }  
  33.     names = string.IsNullOrEmpty(names) ? string.Empty : names.Substring(0, names.LastIndexOf(‘;’));  
  34.     return names;  
  35. }  
Thanks.