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;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
if (site.WebApplication.ContentDatabases.Count > 0)
{
string DBConnString = site.WebApplication.ContentDatabases[0].DatabaseConnectionString;
SqlConnection con = new SqlConnection(DBConnString);
try
{
con.Open();
SqlCommand com = con.CreateCommand();
com.CommandText = String.Format(“SELECT NextAvailableId FROM AllListsAux where ListID = ‘{0}'”, listId.ToString());
id = (int)com.ExecuteScalar();

}
finally
{
con.Close();
}

}
});
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: http://suguk.org/forums/permalink/6226/13513/ShowThread.aspx

One thought on “Get Next List Item ID in Sharepoint List

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.