How can I delete a SharePoint List views programatically?
MyCustomView: is a custom view created by me programatically. I want to delete all view created with same name
using (SPSite oSPsite = new SPSite("http://xxxxxxxxxx:20000/sites/myWA/test"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
SPList oTransDataList = oSPWeb.Lists["MyDataList"];
oSPWeb.AllowUnsafeUpdates = true;
SPViewCollection oViewCollection = oTransDataList.Views;
int i = 1;
foreach (SPView oViewColl in oViewCollection)
{
if (oViewColl.Title == "MyCustomView")
{
oViewCollection.Delete(oViewColl.ID);
//oTransDataList.Views.Delete(oViewColl.ID);
oTransDataList.Update();
}
}
}
}
I noticed SPViewCollection oViewCollection = oTransDataList.Views;
containing 1 view only. May I know why so happening I have more than 10 views out of which 9 views are custom with same name. ie. MyCustomView
It looks like you are on the right track. However, I would recommend doing this in two steps. First, collect the desired views. Second, delete the views. The problem with combining the steps is that the collection you are looping through changes once you delete a view.
using (SPSite oSPsite = new SPSite("http://xxxxxxxxxx:20000/sites/myWA/test"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
SPList oTransDataList = oSPWeb.Lists["MyDataList"];
oSPWeb.AllowUnsafeUpdates = true;
List<Guid> ids = new List<Guid>();
SPViewCollection oViewCollection = oTransDataList.Views;
foreach (SPView oViewColl in oViewCollection)
{
if (oViewColl.Title == "MyCustomView")
{
ids.Add(oViewColl.ID);
}
}
foreach (Guid id in ids)
{
oViewCollection.Delete(id);
}
}
}
As another alternative, you might be able to combine the steps, if you step through the collection backwards:
for (int i = oViewCollection.Count - 1; i >= 0; --i)
{
SPView oViewColl = oViewCollection[i];
if (oViewColl.Title == "MyCustomView")
{
oViewCollection.Delete(oViewColl.ID);
}
}