HOME ABOUT
I AM HERE
  • Twitter icon
  • Facebook icon
  • Technorati icon
Bookmark and Share

Using SPQuery and CAML to filter and order

November 27, 2007 20:18 by Aidan

To get a collection of items from a list you can use SPQuery and CAML to filter and order the selected list:

            SPSite oSite = SPContext.Current.Site;
            SPWeb oWeb = oSite.OpenWeb();
            SPList oList = oWeb.Lists["ListName"];
            SPQuery oQuery = new SPQuery();
            oQuery.Query = "<OrderBy><FieldRef Name='Title' /></OrderBy><Where>"
                + "<FieldRef Name='Title' /><Value Type='Text'></Value></Where>";
            SPListItemCollection oItems = oList.GetItems(oQuery);

To filter on date use the following to get any item that has been modified in the last 7 days:

string dateString = Microsoft.SharePoint.Utilities.
SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today.AddDays(-7));

oQuery.Query = <Where><Geq><FieldRef Name=\"Modified\"/><Value Type=\"DateTime\">"+ dateString+"</Value></Geq></Where>


Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (5) | Comment RSSRSS comment feed

Comments

December 12. 2007 16:46

You also need to Dispose of the Web and Site - easiest way is to put them in a using {} block.

Oskar Austegard

December 14. 2007 12:22

Nooo... Don't dispose of objects that have been obtained from SPContext! SharePoint handles their disposal. Apparently bad things can happen if you dispose of them early! I haven't seen the evidence of this, but it was drummed into me that it's bad to do.

Paul

December 14. 2007 19:25

My bad - I failed to notice the SPContext.Current

My advice would only be valid if you new'ed up a Site.

Sorry.

(Wouldn't it be nice if this was consistent throughout the OM?)

Oskar Austegard

June 23. 2008 16:01

You don't dispose of the oSite object because it is a direct reference of the SPContext but you ALWAYS dispose of the SPWeb generated from OpenWeb().

http://msdn.microsoft.com/en-us/library/aa973248.aspx#sharepointobjmodel__spwebobjects

int i;

SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

oSPWeb = oSPSite.OpenWeb();

for(i = 0;i < oSPWeb.Webs.Count;i++)
{
   oSPWeb2 = oSPWeb.Webs[i];
   BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
   oSPWeb2.Dispose();
}

oSPWeb.Dispose();

richl

October 6. 2009 13:32

Nice !!!!!!!!

SpQuery and CAML in Sharepoint, it is simple.

Try this too,
http://sarangasl.blogspot.com/2009/10/caml-spquery-in-sharepoint.html

sara

Add comment




  Country flag


  • Comment
  • Preview
Loading