Scenario: Create a view in document library  to show all items without folders using object model.



Solution: I first tried this solution but it did not work.
using (SPSite site = new SPSite("http://intranet.contoso.com/sites/contracts"))
{
    using (SPWeb web = site.OpenWeb())
    {
        char[] ViewFieldSepartors = new char[] { ';' };
        string viewFields = "Title;Department";
        SPList list = web.Lists["DOC1"];
        SPQuery query = new SPQuery();
        query.Query = "<QueryOptions><ViewAttributes Scope='Recursive' /></QueryOptions>";
        StringCollection fields = new StringCollection();
        fields.AddRange(viewFields.Split(ViewFieldSepartors, System.StringSplitOptions.RemoveEmptyEntries));
        SPView view = list.Views.Add("TestView", fields, query.Query, 100, true, false);
        list.Update();
    }
}

Then I created the required view using UI and checked the generated CAML using SPManager and found that SPView.Scope property needs to be set to Recursive in order to show all items without folders. Following is the code for that:

using (SPSite site = new SPSite("http://intranet.contoso.com/sites/contracts"))
{
    using (SPWeb web = site.OpenWeb())
    {
        char[] ViewFieldSepartors = new char[] { ';' };
        string viewFields = "Title;Department";
        SPList list = web.Lists["DOC1"];
        StringCollection fields = new StringCollection();
        fields.AddRange(viewFields.Split(ViewFieldSepartors, System.StringSplitOptions.RemoveEmptyEntries));
        SPView view = list.Views.Add("TestView", fields, string.Empty, 100, true, false);
        view.Scope = SPViewScope.Recursive;
        view.Update();
        list.Update();
    }
}


2 comments

  1. Dmitry Dolotovskikh // 12 March 2014 04:42  

    Hi
    We created rule in SPCAFContrib product to check this case. Also for SPQuery.ViewAttributes attribute.

    https://spcafcontrib.codeplex.com/wikipage?title=CSC510205_SPViewScopeDoesNotDefined

  2. Nadeem Yousuf // 12 March 2014 05:08  

    Good to hear that.

My SharePoint CodePlex Projects

SharePoint 2010 Autocomplete Lookup Field

Export Version History Of SharePoint 2010 List Items to Microsoft Excel.