tags:

views:

658

answers:

2

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.

+1  A: 

I know this is not exactly what you hoped for, but SPFiles are buggy with views for a binary copy, so try just passing the same values on the overload:

SPList list = SPContext.Current.Web.Lists["Test"];
SPViewview = list.Views["All Items"];
list.Views.Add(view.Title + "_NEW", view.ViewFields.ToStringCollection(), 
               view.Query, view.RowLimit, view.Paged, view.DefaultView);

You get a new view with a new name and the exact same content.

F.Aquino
Yeah, this is what I'm doing now. I was hoping to go the other route in to pick up any customizations done on the view (GroupHeader/GroupFooter). Thanks though.
confusedGeek
Ok, still haven't found anything that indicates I can do it the way I want. Marking this as the answer (even if I don't really like it).
confusedGeek
+4  A: 

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.

ccomet
@ccomet, Thanks that is exactly what I was looking for. Never occurred to me to check the SPView properties for Clone.
confusedGeek