1
votes

I'm very new to CamlQuery and need a bit of help getting this to work.

I installed a tool called CamlDesigner to help me generate the XML needed to filter a collection in Sharepoint, but the XML query that CamlDesigner constructs does not work in my C# codebehind. I have an ID field that I am trying to filter by and I simply want to retrieve an item from Sharepoint where ID = 1 (or 2 or 3 or whatever).

Here is the Caml query generated by the designer:

   <Where>
      <Eq>
         <FieldRef Name='ID' />
         <Value Type='Counter'>1</Value>
      </Eq>
   </Where>

Here is my C# code where I am attempting to incorporate this Caml query. The C# works, but it is returning every item from "My SP Coll" as opposed to only returning the item where ID equals 1.

// Sharepoint web service to retrieve categories items there
ClientContext clientContext = new ClientContext("https://myweb.dev.com/SP");
List oList = clientContext.Web.Lists.GetByTitle("My SP Coll");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Query><Where><Eq><FieldRef Name='ID'/><Value type='Counter'>" + ID.ToString() + "</Value></Eq></Where></Query>";
Microsoft.SharePoint.Client.ListItemCollection collListItem = oList.GetItems(camlQuery);

clientContext.Load(collListItem);
clientContext.ExecuteQuery();

foreach (Microsoft.SharePoint.Client.ListItem oListItem in collListItem) {
     string ID = oListItem["ID"].ToString();
}

Thanks for the help!

2

2 Answers

2
votes
  1. The query needs to be wrapped in a <View>...</View> element, in addition to the <Query> element.

  2. As per the generated query, the field name is ID not Id.

On a side note, make sure you're disposing of the client context.

And of course, to get an item by ID you can bypass this entire process and just use

var item = list.GetItemById(ID);
1
votes

The ViewXml property just points to a view within a list and doesn't appear to handle filtering.

If you were to set up an already-filtered view and point the ViewXml to that, then you would still grab all items in the view, but since the view itself is filtered, your result set would match it.