Aidan Garnish
MOSS 2007 and other Microsoft technologies

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>


Currently rated 3.3 by 4 people

  • Currently 3.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: MOSS 2007
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

Related posts

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().

msdn.microsoft.com/.../aa973248.aspx

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

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 15:04