To know about the Basics of the CAML query read this article.
Please free to comment and share this post if it helps you!
To know
about using CAML query builder to create
CAML queries, read this article.
In this
article, we will learn how to use CAML query in Microsoft Visual Studio
Scenario:
I have a
custom list named “Product List” with the columns named Title, Price, Quantity
and Is Available.
I want to
retrieve the products with price greater than 1000 and lesser than 10000. Then
I have to order the results depending upon the quantity in descending order.
Using the
CAML query builder, I have created a CAML query for the above scenario and the
query is as follows:
<Query><Where><And><Gt><FieldRef
Name="Price" /><Value
Type="Number">1000</Value></Gt><Leq><FieldRef
Name="Price" /><Value
Type="Number">10000</Value></Leq></And></Where><OrderBy><FieldRef
Name="Price" Ascending="False"
/></OrderBy></Query>
Implementing
CAML Query in Microsoft Visual Studio
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace UsingCAMLQuery
{
class Program
{
static void Main(string[] args)
{
const string camlQuery = @"1000 10000 ";
try
{
using (SPSite objSite = new SPSite("sitename"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
// Building a query
SPQuery query=new SPQuery();
query.Query=camlQuery;
// Retrieving the data from the List
SPList objList=objWeb.Lists["Product List"];
SPListItemCollection items= objList.GetItems(query);
// Prinitng the header
Console.WriteLine("{0,-25} {1,-20} {2,-15} {3}", "Title", "Price", "Qunatity", "Is Available");
foreach (SPListItem objListItem in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}", objListItem["Title"], objListItem["Price"],
objListItem["Quantity"], objListItem["Is Available"]);
}
}
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine("Error Occured:", ex.Message);
}
Console.ReadLine();
}
}
}
The full solution can be downloaded from the following link. Please free to comment and share this post if it helps you!
thanks alot
ReplyDeleteYou are welcome!
DeleteCouln't you reach same results if you work with view for the list?
ReplyDelete