SharePoint: Create Dynamic SPQuery

Scenario:

We need to develop a webpart that searches a list in SharePoint. The search criteria are based upon user input. A simplified image of search criteria is as under:


Resolution:

After googling, we found a great solution:
http://sharepointcamlhelper.codeplex.com/

Suppose we have two checkboxes and two radio button, then our query should be like this:

SPQuery oQuery = new SPQuery();
CAMLManager mgr = new CAMLManager();
mgr.QueryGroups.Add(new QueryGroup("ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Eq, "ColumnValue"));
mgr.QueryGroups.Add(new QueryGroup(Types.JoinTypes.And, "ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Eq, "ColumnValue"));
if (chkSelectGroup.Checked == true)
{
mgr.QueryGroups.Add(new QueryGroup(Types.JoinTypes.And, "ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Eq, ddlSelectGroup.SelectedItem.Text));
}
if (chkSubject.Checked == true)
{
mgr.QueryGroups.Add(new QueryGroup(Types.JoinTypes.And, "ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Contains, txtSubject.Text));
}
if (rbAnnByEmail.SelectedIndex != -1)
{
if (rbAnnByEmail.SelectedItem.Text == "Yes")
{
mgr.QueryGroups.Add(new QueryGroup(Types.JoinTypes.And, "ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Eq, "ColumnValue"));
}
if (rbAnnByEmail.SelectedItem.Text == "No")
{
mgr.QueryGroups.Add(new QueryGroup(Types.JoinTypes.And, "ColumnName", Types.FieldTypes.Text, Types.QueryTypes.Eq, "ColumnValue"));
}
}
mgr.OrderBy.Add(new OrderBy("ColumnName", false));
string camlQuery = mgr.GetFullCAML();
oQuery.Query = camlQuery;

Issue:
One thing that doesn’t seems to be working is “ViewFields”. We have added following lines to restrict our query to specific fields, but it doesn’t seems to be working.

cmgr.ViewFields.Add(new ViewField("ColumnName"));
cmgr.ViewFields.Add(new ViewField("ColumnName"));
cmgr.ViewFields.Add(new ViewField("ColumnName"));
cmgr.ViewFields.Add(new ViewField("ColumnName"));
cmgr.ViewFields.Add(new ViewField("ColumnName"));


Update:
If we add following code, ViewFields seems to work

spQuery.ViewFieldsOnly = true;
spQuery.ViewFields = cmgr.GetViewFields().Replace("", "").Replace("", "");

Advertisements

1 Comment »

  1. Hi there it’s me, I am also visiting this web site oon a reguar basis, this web site is trulky
    nice and the visitors aare really sharing pleasant thoughts.

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: