August 08, 2013

How to Write and Pass CamlQuery to get Sharepoint 2010 / SharePoint 2013 list items in SPQuery or in CamlQuery objects





if in you Client object Model code CamlQuery returning all data or C# Server object model SPQuery / CamlQuery returning all data so there may be issue with way of writing Query, it happens due to small mistake while copy pasting query from caml query builder to our code. It is very small thing that need to take care while pasting query to CamlQuery or SPQuery object,

Client Object Model:

   <View><Query>
            
<Where>
                 <And>
                   <Eq>
                      <FieldRef Name='Title' />
                        <Value Type='Text'>" + t1 + @"</Value>
                   </Eq>                
                 </And>
                </Where>
   </Query></View>


Server Object Model



<View><Query>
            <Where>
                 <And>
                   <Eq>
                      <FieldRef Name='Title' />
                        <Value Type='Text'>" + t1 + @"</Value>
                   </Eq>                 
                 </And>
                </Where>
 </Query></View>



 Sample

         


Code:
using (ClientContext clientContext = new ClientContext(txtSiteUrl.Text))
     {
       CamlQuery oQuery = new CamlQuery();
       oQuery.ViewXml = @"<View><Query><Where>
                                          <And>
                                            <Eq>
                                               <FieldRef Name='Title' />
                                              <Value Type='Text'>" + t + @"</Value>
             </Eq>                                          
                                          </And>
                                       </Where></Query></View>";

     List oList = clientContext.Web.Lists.GetByTitle("myList");
     if (oList != null)
        {
            ListItemCollection  oColl=oList.GetItems(oQuery);
            clientContext.Load(oColl);
            clientContext.ExecuteQuery();   
        }
     }




In short while working in Client object Model you should append your Query between <Query><View> </View></Query>like below:

<View><Query>Your Caml Query</View></Query>

And while working in Server object model remove Query tag from caml query which is copied from caml query builder like 

<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>Praveen</Value></Eq></Where>



Please share any issue or findings in this.

 



 --
Regards,
Praveen Pandit
MCTS; MCPD
Keep Sharing Knowledge!!

No comments:

Post a Comment