I have a standard list in Sharepoint 2010. The list has a standard view, but technically the view could even be custom built.

Is it possible for me to pass through a CAML query from a web part I've built, to filter results in the view?

I intend to implement a tree nav web part, that will filter items - very much in the same way managed metadata filtering works.

I'll need to do recursive lookups so the CAML could end up being "fun". But CAML is pretty good performance wise, so mainly is it possible to get the CAML to the view, so that it filters efficiently?

Thanks in advance!

EDIT: If this is possible, just just a quick hint where the code would go. I've managed to track down this :

SPWeb web = SPControl.GetContextWeb(this.Context);
SPView view = web.Lists["List Name"].Views["Search"];
view.Query = query;

But I guess this would need to be placed inside the view aspx code. Because it would be dynamic each time the view is requested.

2 Answers 2


I would need to know a little more about your specific demands to give a better script, but the code below would hit a calendar list. It is in powershell, but you can convert that over easily. I prefer to not leverage a view and just make the necessary filter changes, which creates a dynamic view. Hope this helps.

$pass = ConvertTo-SecureString "password" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList "domain\svc_acct", $pass

#Region Get SharePoint List Data
$web = New-WebServiceProxy -Uri:"http://webapp/site/_vti_bin/Lists.asmx" -Credential:$creds
$web.url = "http://webapp/site/_vti_bin/Lists.asmx"

$filter = [xml]@"
                    <FieldRef Name='EventDate' />
                    <Value IncludeTimeValue='TRUE' Type='DateTime'>$BeginDate</Value>
                    <FieldRef Name="EventDate" />
                    <Value IncludeTimeValue="TRUE" Type="DateTime">$EndDate</Value>
                <FieldRef Name='Flags' />
                <Value Type='MultiChoice'>PTO</Value>

$viewfields = [xml]@"
      <FieldRef Name="Event_x0020_Owner" />
      <FieldRef Name="EventDate" />
      <FieldRef Name="EndDate" />
$queryoptions = [xml]"<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc></QueryOptions>"
$listName = "Team Calendar"
$rowLimit = "0" 
$items = $web.GetListItems($listName, $viewGUID, $filter, $viewfields, $rowLimit, $queryoptions, $null)

I suppose you could create a custom webpart wrapping the standard ListViewWebPart and dynamically set the query when rendering. See this blog post for a solution like this for SharePoint 2007: http://www.sharepointkings.com/2008/08/create-custom-listviewwebpart.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.