0

I have the following code inside our server-side event receiver, the code should connect to a sharepoint online list and get the total number of items, here is the code:-

   try
   {
     currentItem["Status"] = "Pending";
     if (currentItem.ContentType.Name.ToLower().Contains("project"))
        {

           using (ClientContext context = new ClientContext("https://***.sharepoint.com/"))
           {
             string s = "***";
             SecureString passWord = new SecureString();
             foreach (var c in s)
             passWord.AppendChar(c);
             context.Credentials = new SharePointOnlineCredentials("admin@****.onmicrosoft.com", passWord);
             List list = context.Web.Lists.GetByTitle("Project");
             context.ExecuteQuery();
             var countItems = list.ItemCount;
           }

        }
   }
   catch (Exception e)
   {
     var errormessage = e.Message;
   }

but i am getting this exception:-

Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException was caught
  HResult=-2146233079
  Message=The property or field 'ItemCount' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
  Source=Microsoft.SharePoint.Client.Runtime
  StackTrace:
       at Microsoft.SharePoint.Client.ClientObject.CheckUninitializedProperty(String propName)
       at Microsoft.SharePoint.Client.List.get_ItemCount()
       at OrderManagement.EventReceiver1.EventReceiver1.ItemUpdated(SPItemEventProperties properties)
  InnerException: 

So can anyone advice how i can fix this issue?

0

You didn't load the list yet.

using (ClientContext context = new ClientContext("https://tenant.sharepoint.com/sites/lee"))
            {
                string s = "password";
                SecureString passWord = new SecureString();
                foreach (var c in s)
                    passWord.AppendChar(c);
                context.Credentials = new SharePointOnlineCredentials("user@tenant.onmicrosoft.com", passWord);
                List list = context.Web.Lists.GetByTitle("TestList");
                context.Load(list);
                context.ExecuteQuery();
                var countItems = list.ItemCount;
                Console.WriteLine(countItems);
            }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.