How to Create – Update – Delete SharePoint Views Programmatically?
Often in development we may have to deal with SharePoint Views programmatically. Here I’m sharing the code snippets from my recent project to handle views programmatically.
Creating a New View Programmatically:
using (SPSite site = new SPSite("https://crescent.sharepoint.com"))
{
using (SPWeb web = site.OpenWeb())
{
//Get the List
SPList ProjectDocuments = web.Lists["Client Documents"];
//Set the View fields
StringCollection ViewFields = new StringCollection();
ViewFields.Add("Type");
ViewFields.Add("Name");
//Set the View Filter and Sort order
string viewQuery = @" <Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>In Progress</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy> ";
//Create the view
ProjectDocuments.Views.Add("Proposal Documents", ViewFields, ViewQuery, 100, true, false);
//Update the List
ProjectDocuments.Update();
}
}
Add/Remove fields to an existing View Programmatically:
//Get the List
SPList ProjectDocuments = web.Lists["Project Documents"];
//Get the view
SPView ProjectDocumentsDV = ProjectDocuments.DefaultView;
// Or it can be: SPView oView = oList.Views["View-Name"];
//Delete all fields from the view
ProjectDocumentsDV.ViewFields.DeleteAll();
//Add "Type" and "Name" fields
ProjectDocumentsDV.ViewFields.Add("Type");
ProjectDocumentsDV.ViewFields.Add("Name");
//Update the view
ProjectDocumentsDV.Update();
//Update the List
ProjectDocuments.Update();
Get the Fields from View Programmatically:
SPView ProjectDocumentsView = ProjectDocuments.DefaultView;
//Get the fields from a View
SPViewFieldCollection ViewFieldColl = ProjectDocumentsView.ViewFields;
foreach (string ViewField in ViewFieldCol)
{
Console.WriteLine("Field Name : " + ViewField);
}
Delete Existing View Programmatically:
//Get the List
SPList ProjectDocuments = web.Lists["Project Documents"];
//Get the view
SPView ProjectDocumentsView = ProjectDocuments.DefaultView;
//Delete the views
ProjectDocuments.Views.Delete(ProjectDocumentsView.ID);
ProjectDocuments.Update();
PowerShell Script to Create – Update – Copy – Delete SharePoint List Views: How to Create / Update / Copy / Delete SharePoint Views with PowerShell?
hai,
can anyone plz help me to how can i get aspx code of our sharepoint page?
Very concise & concrete code, thanks.
Hello
Simple and great example. Can you please tell me how do I parse through all the rows of a Sharepoint 2010 personal/custom created “View (not Sharepoint List)” using the Sharepoint Client Object Model (Microsoft.Sharepoint.client)?
Thanks,
Mehul
Hi Mehul,
You can get rows from a SharePoint view. Please have a look at these links.
https://sharepoint.stackexchange.com/questions/28446/how-to-get-all-items-in-a-view-using-client-object-model-javascript
https://msdn.microsoft.com/en-us/library/ms425858.aspx (server object model, But will give you an idea)
Nice article 🙂