Sunday, January 4, 2015

Allow CAML Query to get items inside Library Folders

Usually a CAML query would query a SharePoint library and get all available items matching the where clause, except the ones within folders of the Library. There is a property which needs to be explicitly set, in order for the query to return all items pertaining to the where clause, including the ones inside folders and nested folders. In the view attribute, the scope needs to be set to Recursive All. A sample CAML query would be:


SPListItemCollection itemCollection = null;
...
...
SPQuery myQuery = new SPQuery();

myQuery.ViewFields = @"<FieldRef Name='UniqueId'/>
                                            <FieldRef Name='ContentType'/>
                                            <FieldRef Name='ID'/><FieldRef Name='FileLeafRef'/>";

                string whereClause = @"<Where>
                                    <Eq>
                                        <FieldRef Name='" + myVariableOne + @"' />
                                            <Value Type='Text'>" + myVariableTwo + @"</Value>
                                    </Eq>
                                  </Where>";

myQuery.Query = whereClause;
myQuery.ViewAttributes += " Scope='RecursiveAll'";


Now use the SPLists GetItems() method to execute the query
Eg: testLibrary.GetItems(myQuery);




No comments:

Post a Comment