Wednesday, August 5, 2009

How to get the last element that was added to a SharePoint list

This is so simple yet I could not find anything on the net .... but lucky for you i'm smart like that ... J

So my scenario:

I needed to get the last item added a list which doesn't seem like a hard thing to do but the way in which I was doing it was not the most efficient. So what I was doing was running through the list with a FOR LOOP and finding the last element. Only problem with this is that the list will eventually get very big and this can affect performance.

So the other more efficient solution is converting the list to a data table and then just pulling the last element in the table ... doesn't that sound a whole lot simpler... so here is the code =>

SPList targetList = web.Lists["SomeList"];

DataTable dt = targetList.Items.GetDataTable();

string lastID = (dt.Rows[dt.Rows.Count-1]["ID"]).ToString();

ok so once you get the ID you can find the item in the list by=>

SPListItem item = l.Items.GetItemById(Convert.ToInt32(lastID));

I hope people find this useful

Till the next problem...

 

No comments:

Post a Comment