Link to home
Avatar of brendanlefavre
brendanlefavreFlag for United States of America

asked on

SPListItem

How can I get the last entry in a list? The example below will gain me access to the items in a list, but I'm getting stuck on how to get the last item submitted.

using (SPSite siteCol = new SPSite("http://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        SPListItemCollection items = list.GetItems("Title", "LogIDNumber",);
    }
}

Open in new window


Cheers,
Brendan
Avatar of abhitrig
abhitrig
Flag of United States of America image

Use a CAML query to get the items and get the last item in the result.

<Query>
    <OrderBy>
            <FieldRef Name="LogIDNumber" Ascending="FALSE" />
    </OrderBy>
</Query>


If you  want the last modified/created  item, you can also use the modified/created by field
Avatar of Jamie McAllister
Something like this should do it.
SPQuery query = new SPQuery();
 query.Query = "<OrderBy><FieldRef Name='Created'
Ascending='FALSE' /></OrderBy>";
query.RowLimit = 1;
SPListItemCollection col = myList.GetItems(query);
                           
if (col.Count > 0)
{
  //do something
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Member_6283346
Member_6283346

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of brendanlefavre

ASKER

this helped me resolve my issue

Cheers,
Brendan