Return to Snippet

Revision: 21101
at December 3, 2009 11:38 by blackf0rk


Initial Code
SPSite site = new SPSite("sharepoint site URL");
int NextID = 0;
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 tp_NextAvailableId from AllLists where tp_ID = '{0}'", listId.ToString());
              NextID = (int)com.ExecuteScalar();
       }
       finally
       {
              con.Close();
       }
}

Initial URL
http://www.codedigest.com/Articles/Sharepoint/279_How_do_I_tell_what_the_next_list_item_ID_is.aspx

Initial Description
In order to accurately get the next ID from a SharePoint list you need to access the content database for one reason: If you delete all the items from a list, and execute this simple code: list.Items[list.ItemCount -1].ID) + 1 the ID will always return 0 when in reality the real ID of the next ID will be the auto-increment number in the content database.

Note that list.Items[list.ItemCount -1].ID) + 1 will work as long as one record is always kept in the list and is never deleted.

Initial Title
Next SPListItem ID From SPList

Initial Tags
list, sharepoint

Initial Language
C#