Search code examples
c#sharepointwindows-sharepoint-services

Adding a cloned SPView to a list


Ok, does anyone know how/if you can clone a SharePoint view and then add it to a list. The SPViewCollection.Add overloads will not take an instance of SPView and I couldn't find any documentation that indicated how to do so.

For example I would like to essentially do this:

var myList = SPContext.Current.Web.List;//or something similar
var baseView = myList.DefaultView;
var myNewView = baseView.Clone("my view", base.RowLimit, base.Paged, false);
myNewView.Query = "<Where>......</Where>";
myList.Views.Add(myNewView);//this overload doesn't exist!

The end result is I want the new View to copy the behavior of the original view with the exception of an altered query. I'm willing to go a different route, but I'm not sure what that is. (I noticed the BaseViewID property that may help, but it's read-only).

Any suggestion or hints would be appreciated.


Solution

  • If you clone an SPView using SPView.Clone(title, rowlimit, paged, default), then it is automatically added to that list as a new view. Or, at least, it is when you call Update() (much like SPList.Items.Add()). I do the following, for example, to create a cloned view that differs only in the query:

    SPView thisView = thisList.DefaultView;
    thisView = thisView.Clone("High Priority", 100, true, false);
    thisView.Query = "<GroupBy Collapse=\"TRUE\" GroupLimit=\"100\"><FieldRef Name=\"dlCategory\" /></GroupBy><Where><Eq><FieldRef Name=\"dlPriority\"></FieldRef><Value Type=\"Number\">2</Value></Eq></Where>";
    thisView.Update();
    

    And now my list (thisList, as it were) has a new view that has all the same properties as the default view except now it groups by a column "dlCategory" and filters out anything whose "dlPriority" is not 2. It's been months since you posted this but I figured I'd leave this out for anyone else who runs across this while doing a search for this stuff.