5

i ve some problem in accessing last record from sharepoint list through CAML query,can any one help me in this regrad;i have a sample list called 'MainHeads' which contains the information like HeadID,Category,and headName....

Mehboob Pakistan

Tobu
  • 24,771
  • 4
  • 91
  • 98
Mehboob Ali
  • 51
  • 1
  • 1
  • 3

3 Answers3

5
<View>
<RowLimit>1</RowLimit>
<Query>
   <OrderBy>
      <FieldRef Name='Created' Ascending='False' />
   </OrderBy>
</Query>
</View>
Francisco Aquino
  • 9,097
  • 1
  • 31
  • 37
3
<View> 
<RowLimit>1</RowLimit> 
<Query> 
   <OrderBy> 
      <FieldRef Name='ID' Ascending='False' /> 
   </OrderBy> 
</Query> 
</View>
Shoban
  • 22,920
  • 8
  • 63
  • 107
Hojo
  • 935
  • 1
  • 7
  • 13
2

Building on this answer I gave to a related question, I would suggest the following query:

SPListItem lastItem;

try
{
    using (SPSite objSite = new SPSite(sSiteUrl))
    {
        using (SPWeb objWeb = objSite.OpenWeb())
        {
            SPList objList = objWeb.Lists["MainHeads"];

            SPQuery objQuery = new SPQuery();
            objQuery.Query = "<OrderBy><FieldRef Name='HeadID' Ascending='False' /></OrderBy><RowLimit>1</RowLimit>";
            objQuery.Folder = objList.RootFolder;

            // Execute the query against the list
            SPListItemCollection colItems = objList.GetItems(objQuery);

            if (colItems.Count > 0)
            {
                lastItem = colItems[0];
            }
        }
    }
}
catch (Exception ex)
{
    ...
}

return lastItem;

This assumes that you are executing the CAML in code. IF not, see F. Aquino's answer.

Community
  • 1
  • 1
Tangiest
  • 43,737
  • 24
  • 82
  • 113