18

I have already created a webpart to show the data from list, but I really want is to only show top 5 records from that list (by using CAML query).

Does anyone know how to do this? Many thanks.

<Query>
   <OrderBy>
      <FieldRef Name='ID' Ascending='False' />
   </OrderBy>
</Query>
Daoming Yang
  • 1,325
  • 3
  • 20
  • 41

3 Answers3

23

You could set the RowLimit property of your SPQuery object.

The <RowLimit> tag is in the schema definition of a view (direct child of <View>) and therefore cannot be nested inside a <Query> tag.

Tudor Olariu
  • 1,318
  • 1
  • 11
  • 18
  • 1
    If I use this query - 10 - I'm getting an error 'There are multiple root elements'. Any ideas? – NLV Aug 02 '11 at 09:09
  • Do not put in the Query; the SPQuery object has a separate property called View which you need to use, and also a RowLimit if I remember correctly – Tudor Olariu Aug 03 '11 at 13:56
10

The below code shows top 5 records from the list (by using CAML query).

SPQuery spQuery = new SPQuery();
spQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>";
spQuery.RowLimit = 5;
David
  • 15,652
  • 26
  • 115
  • 156
0

If you want to construct other simply caml queries try this tool. http://www.camldesigner.com/

P.s. tool doesn`t construct a "paginate" caml queries with SPListItemCollectionPosition.

k.makarov
  • 854
  • 1
  • 12
  • 28