18 January 2022

How to get the following ID in a SharePoint list

 hi...

More than a decade ago .. I wrote a kwizcom blog article - how to get the following ID in a SharePoint list

https://kwizcom.blogspot.com/2009/08/how-do-i-tell-what-next-list-item-id-is.html

This was valid for SharePoint 2007 and 2010 for sure.

I do not know when Microsoft changed the table in the database ..

But now in SharePoint 2019 they have created another table AllListsAux and the code should look like this

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

/// < name="site">site

/// < name="listId">listId

///

public static int SharePointListNextItemId(SPSite site, Guid listId)

{

    int id = -1;

    SPSecurity.RunWithElevatedPrivileges(delegate ()

    {

        if (site.WebApplication.ContentDatabases.Count > 0)

        {

            string DBConnString = site.WebApplication.ContentDatabases[0].DatabaseConnectionString;

            using (SqlConnection con = new SqlConnection(DBConnString))

            {

                try

                {

                    con.Open();

                    using (SqlCommand command = con.CreateCommand())

                    {

                        command.CommandText = String.Format("select NextAvailableId from [AllListsAux] where ListID = '{0}'", listId.ToString());

                        id = (int)command.ExecuteScalar();

                    }

                }

                finally

                {

                    con.Close();

                }

            }

        }

    });

    return id;

}

Hope this helps!