SharePoint list query is a powerful feature that allows you to retrieve specific data from your SharePoint lists. Here’s how to implement it:
To start, you’ll need to create a new SharePoint web part page or use an existing one. Next, add a “Content Editor Web Part” to the page and give it a title. This will be where we’ll put our code.
Step 1: Create a CAML query
A CAML (Collaborative Application Markup Language) query is used to retrieve specific data from your SharePoint lists. You can use the SharePoint designer or write the code manually. Here’s an example of how you might create a simple CAML query that retrieves all items from a list:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/sites/contenttype">
<ListInstance Title="My List" TemplateType="100"></ListInstance>
<Query>
<Where>
<Eq>
<FieldRef Name="ContentType" />
<Value Type="Text">Document</Value>
</Eq>
</Where>
</Query>
</Elements>
This query retrieves all items from a list where the content type is “Document”.
Step 2: Add the query to your web part
To add the query to your web part, you’ll need to use SharePoint’s object model. First, you’ll need to reference the SharePoint DLLs in your project:
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
Next, create a new SPSite object and pass it the URL of your SharePoint site:
SPSite oSPSite = new SPSite("http://your-sharepoint-site.com");
Then, use the SPSite object to get a reference to the list you want to query:
SPWeb oSPWeb = oSPSite.OpenWeb();
SPList oSPList = oSPWeb.Lists["My List"];
Finally, execute the CAML query using the SPQuery class:
SPQuery oSPQuery = new SPQuery(oSPList);
oSPQuery.Query = "<Elements xmlns=\"http://schemas.microsoft.com/sharepoint/sites/contenttype\">" +
" <ListInstance Title=\"My List\" TemplateType=\"100\"></ListInstance>" +
" <Query>" +
" <Where>" +
" <Eq>" +
" <FieldRef Name=\"ContentType\" />" +
" <Value Type=\"Text\">Document</Value>" +
" </Eq>" +
" </Where>" +
" </Query>" +
"</Elements>";
SPListItemCollection oSPListItems = oSPList.GetItems(oSPQuery);
This will return a collection of SPListItem objects that match the query.
Step 3: Loop through the results
To loop through the results, you can use a foreach loop:
foreach (SPListItem item in oSPListItems)
{
// Do something with each item
}
That’s it! With these steps, you should be able to implement a SharePoint list query and retrieve specific data from your lists.