Create View in SharePoint using CSOM

The example in this topic show how to use CSOM to Create View in SharePoint

  • using Microsoft.SharePoint.Client;
  • using System.Linq;
  •  
  • using (ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection"))
  • {
  • // clientcontext.Web.Lists.GetById - This option also can be used to get the list using List GUID
  • // This value is NOT List internal name
  • List targetList = clientcontext.Web.Lists.GetByTitle("List Name");
  •  
  • ViewCollection viewCollection = targetList.Views;
  • clientcontext.Load(viewCollection);
  •  
  • ViewCreationInformation viewCreationInformation = new ViewCreationInformation();
  • viewCreationInformation.Title = "View Name";
  •  
  • // Specify type of the view. Below are the options
  •  
  • // 1. none - The type of the list view is not specified
  •  
  • // 2. html - Sspecifies an HTML list view type
  •  
  • // 3. grid - Specifies a datasheet list view type
  •  
  • // 4. calendar- Specifies a calendar list view type
  •  
  • // 5. recurrence - Specifies a list view type that displays recurring events
  •  
  • // 6. chart - Specifies a chart list view type
  •  
  • // 7. gantt - Specifies a Gantt chart list view type
  •  
  • viewCreationInformation.ViewTypeKind = ViewType.Html;
  •  
  • // You can optionally specify row limit for the view
  • viewCreationInformation.RowLimit = 10;
  •  
  • // You can optionally specify a query as mentioned below.
  • // Create one CAML query to filter list view and mention that query below
  • viewCreationInformation.Query = "<Where><Eq><FieldRef Name = 'Location' /><Value Type = 'Text'>India</Value></Eq></Where>";
  •  
  • // Add all the fields over here with comma separated value as mentioned below
  • // You can mention display name or internal name of the column
  • string CommaSeparateColumnNames = "Column name 1, column Name 2, Column Name 3";
  • viewCreationInformation.ViewFields = CommaSeparateColumnNames.Split(',');
  •  
  • View listView = viewCollection.Add(viewCreationInformation);
  • clientcontext.ExecuteQuery();
  •  
  • // Code to update the display name for the view.
  • listView.Title = "View Display Name";
  •  
  • // You can optionally specify Aggregation: Field references for totals columns or calculated columns
  • listView.Aggregations = "<FieldRef Name='Title' Type='COUNT'/>";
  •  
  • listView.Update();
  • clientcontext.ExecuteQuery();
  • }

Thank you for reading this article. This code was tested in SharePoint 2013


© 2019 Code SharePoint