Create, Retrieve, and Delete the View of a SharePoint List using Client Object Model

string siteUrl = "http://servername:12345/";
ClientContext ctx = new ClientContext(siteUrl);
List oList = ctx.Web.Lists.GetByTitle("ListTitle");

Retrieve Views

SP.ViewCollection viewCollection = oList.Views;
ctx.Load(viewCollection);
ctx.ExecuteQuery();

Delete all the Views

foreach (SP.View vw in viewCollection)
{
	Microsoft.SharePoint.Client.View view = oList.Views.GetByTitle(vw.Title);
	ctx.Load(view);
	view.DeleteObject(); // Delete Existing views
	ctx.ExecuteQuery();
}

Create a new View

SP.ViewCreationInformation viewCreationInformation = new SP.ViewCreationInformation();
viewCreationInformation.Title = "New View";
viewCreationInformation.ViewTypeKind = SP.ViewType.None;
viewCreationInformation.RowLimit = 30;//Make sure that the name of the fields should be equal to 1 any of the associated SiteColumns Internal Name. The Fields in the view will appear in the same order as declared here.
viewCreationInformation.ViewFields = new string[]{"Title","Created","Modified"};
viewCreationInformation.SetAsDefaultView = true;
oList.Views.Add(viewCreationInformation);

ctx.Load(oList.Views);
ctx.ExecuteQuery();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.