Can someone tell me what I am doing wrong here? I trying to pass the list name to a method that would delete all the rows in the list:
public static void DeleteLastUpdate(Microsoft.SharePoint.Client.List oList)
{
using (var context = new ClientContext(FrontEndAppUrl))
{
var ss = new System.Security.SecureString();
Array.ForEach("hhh".ToCharArray(), (c) => { ss.AppendChar(c); });
context.Credentials = new SharePointOnlineCredentials("yyy", ss);
var web = context.Web;
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy></Query></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
context.Load(collListItem);
context.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
string i = oListItem["ID"].ToString(); ;
ListItem ListItemToDelete = oList.GetItemById(i);
ListItemToDelete.DeleteObject();
context.ExecuteQuery();
}
oList.Update();
}
}
public static void GetCountry()
{
using (var context = new ClientContext(FrontEndAppUrl))
{
Microsoft.SharePoint.Client.List oList_Country = context.Web.Lists.GetByTitle("LISTNAME");
DeleteLastUpdate(oList_Country);
}
}
The error I am getting is at context.Load(collListItem);
It says The object is used in the context different from the one associated with the object. How else can I pass the value of the list to the Delete() method?
Exactly what the exception says is what is happening. You create the oList_Country
in the context of GetCountry()
and then pass it to DeleteLastUpdate()
where you are working within a different context.
Maybe you should think about passing the context to DeleteLastUpdate()
via a parameter. Then your code would become something like this:
public static void DeleteLastUpdate(ClientContext context, Microsoft.SharePoint.Client.List oList)
{
// You should not create a context here, but use the supplied context
// using (var context = new ClientContext(FrontEndAppUrl))
// {
var ss = new System.Security.SecureString();
...
}
public static void GetCountry()
{
using (var context = new ClientContext(FrontEndAppUrl))
{
Microsoft.SharePoint.Client.List oList_Country = context.Web.Lists.GetByTitle("LISTNAME");
DeleteLastUpdate(context, oList_Country); // Pass the context