7

I have a CAML query that queries a calendar list and I want it to return all the items in the list with an EventDate of today or later, ordered in ascending order. The CAML query I'm using is this:

<Query><Where><Geq><FieldRef Name="EventDate" /><Value Type="DateTime"><Today/></Value></Geq></Where><OrderBy><FieldRef Name="EventDate" Ascending="True" /></OrderBy></Query> 

When I run the query in U2U's CAML builder I see the results I expect but when it's run in the WebPart I'm using to render the list into a page all of the items are fetched including those with a date earlier than today. Here's the relevant part of the code:

Dim site As SPSite = SPContext.Current.Site Using web As SPWeb = site.OpenWeb Dim controlHTML As New StringBuilder() Try Dim list As SPList = web.Lists("Diary") defaultViewURL = list.DefaultViewUrl controlHTML.Append(FirstPart) Dim itemsByDateQuery As New SPQuery itemsByDateQuery.Query = "<Query><Where><Geq><FieldRef Name=""EventDate"" /><Value Type=""DateTime""><Today/></Value></Geq></Where><OrderBy><FieldRef Name=""EventDate"" Ascending=""True"" /></OrderBy></Query>" Dim items As SPListItemCollection = list.GetItems(itemsByDateQuery) Dim itemsToShowCount As Integer = Math.Min(items.Count, Me.ItemsToShow) controlHTML.AppendLine(DiaryTable(items, itemsToShowCount)) controlHTML.AppendLine("<p>" & System.Web.HttpUtility.HtmlEncode(itemsByDateQuery.Query) & "</p>") Catch ex As Exception controlHTML.AppendLine(String.Format("<p>Couldn&rsquo;t render the list. The error was {0}", ex.Message)) End Try controlHTML.AppendLine(LastPart) Me.Controls.Add(New LiteralControl(controlHTML.ToString)) End Using 

Am I missing something obvious here? I don't understand why the query is returning items with an EventDate earlier than today when run in the WebPart but not when the CAML is run in CAML Builder.

1
  • Please tag by feature or topic and not by version or product. This helps to attract more attention to your question and keep it relevant. See How do I use tags for general guidelines. Commented Aug 31, 2011 at 3:46

1 Answer 1

13

You should remove <Query> and </Query> and use only inner XML. So in your case the .Query should be:

itemsByDateQuery.Query = "<Where><Geq><FieldRef Name=""EventDate"" /><Value Type=""DateTime""><Today/></Value></Geq></Where><OrderBy><FieldRef Name=""EventDate"" Ascending=""True"" /></OrderBy>" 
2
  • 3
    A classic error with CAML :-) Commented Apr 27, 2011 at 11:10
  • Thanks. I've not done any CAML for a few months so I'd forgotten about that. Commented Apr 28, 2011 at 13:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.