Home » Articles


CodeDigest Navigation

Technology News
No News Feeds available at this time.

Community News
No News Feeds available at this time.
How to Get Next List Item ID in Sharepoint List?

By Roi Kolbinger
Posted On Aug 11,2009
Article Rating:
Average Rating: 3
No of Ratings: 1
No of Comments: 0
Category: Sharepoint/MOSS
Print this article.

How to Get Next List Item ID in Sharepoint List?


By Roi Kolbinger - SharePoint Consultant

KWizCom Professional Services –


If you have ever worked with Event Handlers on an item you probably came across the same problem that was bothering me…


I created a ListItem and used the event handler ItemAdding (for a synchronic event). I tried to find out what my ID was but the value I got was zero.


This problem will not occur on ItemAdded (of a non-synchronic 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 avoid getting the zero value) of my synchronic event I wrote this 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 for a SharePoint API that would give me the next item ID but found none. It seemed no one had tackled this problem….


After extensive searching I found a solution, brilliant in its simplicity. This is the code:


/// <summary>

/// Get the next available item id from a list

/// </summary>

/// < param name="site">site</param>

/// < param name="listId">listId</param>

/// < returns></returns>

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 tp_NextAvailableId from AllLists where tp_ID = '{0}'", listId.ToString());

            id = (int)com.ExecuteScalar();








   return id;




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


As you can see, the solution is to connect to the MOSS database and read the ID AllList table. All the information was right there, we simply had to access it.

Now you know how to get the next ID of the ListItem and (hopefully!) Event Handlers will no longer give you any trouble!...



The solution detailed in this article was found at:

Similar Articles