Ads

Saturday, 23 March 2013

C# code get the next item ID for a SharePoint list programatically

Its easy to check the ID after adding one item in sharepoint list.
If we want to get the next ID that will generate before adding the item then follow the code below. 
public static int NextListItemID(SPSite oSite, Guid listId)
{
      int listItemId = -1;
      Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
        {
                 if (oSite.WebApplication.ContentDatabases.Count > 0)
                 {
                   //Get the connection string for the sharepoint database
                            string connString = oSite.WebApplication.ContentDatabases[0].DatabaseConnectionString;
 
                           //Establish a connection
            SqlConnection con = new SqlConnection(connString);
                           try
                           {
                                 con.Open();
  
    //Query to get the next item id for a list(Filtering the list by the list id)
                               SqlCommand com = con.CreateCommand();
      com.CommandText = String.Format("select tp_NextAvailableId from AllLists where tp_ID = '{0}'", listId.ToString());
                               listItemId = (int)com.ExecuteScalar();
                          }
                        finally
                        {
                               con.Close();
                        }
                 }
       });
      return listItemId;
}

No comments:

Post a Comment

Ads