Continuing my series of posts about provisioning sharepoint elements programmatically through object model, today I would like to show how to provision a view associated with a list programmatically (as opposed to using CAML).
One can create as many views as you want in addition to the default view. The views will be accessable through a view dropdown on the right side of the list screen.
In order to create a view, one shoild first create a StringCollection of all the columns that should be displayed. For example to create a view consisting of title and content type name, do the following:
//create string collection of columns that are part of the view
StringCollection viewFields = new StringCollection();
viewFields.Add("LinkTitele");
viewFields.Add("ContentType");
Notice that if you want to be able to link to open individual list items you must include “LinkTitle” column, otherwise this view will be sort of read-only, not allowing you to view or edit list line items. If you need to have title column in the view but specifically do not want to give the user ability to open individual items from this view, iinclude “Title: column instead of “LinkTitle”. That should do the trick.
Once the string collection is prepared, one can create the view by calling SPList.Views.Add() method, passing the viedw name, string collection, XML query defining view filter and order settings, row limit and two booleans: bPaged and bMakeViewDefault:
//create view
SPView sortByTitleView = list.Views.Add("Sort By Title", sortByStatusViewFields, "<OrderBy><FieldRef Name="LinkTitle"/></OrderBy>", 100, true, false);
The code above creates a view that sorts items by Title column. Once the view is added all one needs to Update() it.
//update view
sortByTitleView.Update();
Here is the complete code:
//create string collection of columns that are part of the view
StringCollection viewFields = new StringCollection();
viewFields.Add("LinkTitele");
viewFields.Add("ContentType");
//create view
SPView sortByTitleView = list.Views.Add("Sort By Title", sortByStatusViewFields, "<OrderBy><FieldRef Name="LinkTitle"/></OrderBy>", 100, true, false);
//update view
sortByTitleView.Update();
As always, if you see any mistakes or inaccuracies in this blog, please let me know.
Hii,
I have created view and every condition is getting updated but the issue is it requires one refresh. that is view condition gets updated only after page refresh and the problem is if i try to refresh the page in code than it gives multiple refresh error.
Can you please assist on this?
Thanks 🙂