Wednesday, January 12, 2011

Sharepoint 2007: C# Building Dynamic SPQuery to Query a Sharepoint List

If you are developing a Sharepoint page or Sharepoint web part which requires writing or constructing dynamic SPQuery or query, such as a Search Criteria page where users can choose to enter one or more search criteria. You can use Caml.cs to construct the SPQuery dynamically. The following example shows you how you can write you dynamic SPQuery using caml.cs helper class.

The following example shows how you can generate dynamic query.


//Build Search String Query 
//Product ID
if (strProdID != "")
    clauses.Add(Caml.Eq("" + strProdID + ""));
//Product Name
if (strProdName != "")
    clauses.Add(Caml.Contains("" + strProdName + ""));
//Product Classification
if (strProductClassification != "0")
    clauses.Add(Caml.Eq("" + strProductClassification + ""));
//Division
if (strDivision != "0")
   clauses.Add(Caml.Eq("" + strDivision + ""));
//Product Manager
if (uvcProdManager.Count != 0)
    clauses.Add(Caml.Eq("" + uvcProdManager[0].User.ID.ToStringSafe() + ""));

//append where 
if (clauses.Count != 0 )
    query.Query = Caml.Where(Caml.And(clauses));
query.Query += Caml.OrderBy("ID", false);

2 comments:

Anonymous said...

I am a little confused. This seems like a partial solution. Where do I find the Caml.cs file?

chienyiing said...

There are few available CAML helper class which you can use:

1) http://sharepointcamlhelper.codeplex.com/

2) https://camldotnet.svn.codeplex.com/svn/JohnHolliday.Caml.Net/CAML.cs