Get Next List Item ID in Sharepoint List

If you have worked with Event Handlers on an item you undoubtedly came across the same problem that was troubling me. I created a ListItem and used the event handler ItemAdding (for a synchronic event). I tried to catch on what my ID was but the value I got was zero.

This issue will not happen on ItemAdded (non-synchronize event) because the item is created separately and it has its own ID. If you use the code below on ItemAdding, you will get a zero value on listItem ID.

SPList list = web.Lists[properties.ListId];

SPListItem listItem = list.Items[properties.ListItem.UniqueId];

int itemId = listItem.ID; // itemId  always zero on ItemAdding event

To discover the ID (and to avoid getting zero) of my synchronize event I wrote the below code:

int itemId = list.Items[list.ItemCount – 1].ID + 1;

This code will work well as long as you do not delete the last item and do not add more than one item simultaneously. If you do the sum you will get will be incorrect. I searched in msdn but it give the impression no one had attempted this problem. After wide searching I found a solution. This is the code:

public static int NextItemID(SPSite site, Guid listId)
int id = -1;
if (site.WebApplication.ContentDatabases.Count > 0)
string DBConnString = site.WebApplication.ContentDatabases[0].DatabaseConnectionString;
SqlConnection con = new SqlConnection(DBConnString);
SqlCommand com = con.CreateCommand();
com.CommandText = String.Format(“SELECT NextAvailableId FROM AllListsAux where ListID = ‘{0}'”, listId.ToString());
id = (int)com.ExecuteScalar();


return id;


int itemId = NextItemID(new SPSite(properties.SiteId), properties.ListId);

The solution is to connect to the SharePoint Content Database and read the ID AllList table we simply have to access it. Now you know how to get the next ID of the ListItem and (positively!) Event Handlers will not give you any issue

The solution explained in this article was found at:


About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

One Response to Get Next List Item ID in Sharepoint List

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: