Dowemo
0 0 0 0


Question:

I have a custom search webpart in Sharepoint which have 7 filters. I am getting data from a Sharepoint list using CAML Query. I want to write a generalized SPQuery which will filter out the data based on the search parameters. The search parameters are optional . If user enters any 2 parameters then I need to get data corresponding to those 2 parameters specified. How do I use CAML Query to achieve this? I am unable to think of a generalized approach for generating my caml query based on search parameters..


Best Answer:


Here is a bit of code I used in Silverlight to generate a CAML query based on search parameters. Maybe it is helpful.

    private ClientContext context;
    private Microsoft.SharePoint.Client.List SampleSPList;
    private Microsoft.SharePoint.Client.ListItemCollection SampleSPCollection;
    //Load the List
    void LoadList()
    {
        SampleSPList = context.Web.Lists.GetByTitle("Sample");
        context.Load(SampleSPList);
        CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
        string camlQueryXml = "";
        bool existsWhere = false;
        if (searchString.Text != "")
        {
            camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleString' /><Value Type='Text'>" + searchString.Text + "</Value></Contains>";
            if (existsWhere == true) {
                camlQueryXml = "<And>" + camlQueryXml + "</And>";
            }
            existsWhere = true;
        }
        if (searchTextArea.Text != "")
        {
            camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleTextArea' /><Value Type='Text'>" + searchTextArea.Text + "</Value></Contains>";
            if (existsWhere == true)
            {
                camlQueryXml = "<And>" + camlQueryXml + "</And>";
            }
            existsWhere = true;
        }
        if (existsWhere == true) { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy><Where>" + camlQueryXml + "</Where></Query></View>"; }
        else { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"; }
        query.ViewXml = camlQueryXml;
        SampleSPCollection = SampleSPList.GetItems(query);
        context.Load(SampleSPCollection);
        context.ExecuteQueryAsync(ListLoaded, ListLoadFailed);
    }



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs