Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am wanting to create a new default view for ALL document libraries on an intranet. How do I go about this without manually updating the All Items (default view) of each document library.

share|improve this question

1 Answer 1

If this is a one time thing then a Console Application would work in this case. If it was SharePoint 2010 I would have recommended powershell.

You want to loop each site collection, each web, look for each Document Library either by name or type, then Create a View, Set View as Default.

 public static void CreateView(SPList list)
        {
            if (list != null)
            {
                SPDocumentLibrary library = (SPDocumentLibrary)list;
                var views = library.Views;
                //Set the viewFields
                var strCollViewFields = new StringCollection { "Type", "LinkFilename", "Modified", "Modified By", "Checked Out To", "Content Type" };
                var strQuery =
                    @"<OrderBy><FieldRef Name='Modified' Ascending='FALSE'/></OrderBy><Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer'/></Value></Eq></Where>";

                views.Add("My new view name", strCollViewFields, strQuery, 30, true, false);
            }
        }

Then to set the default view

public static void SetDefaultView(SPList list)
        {
            if (list != null)
            {
                SPDocumentLibrary library = (SPDocumentLibrary)list;
                SPView view = library.Views["My new view name"];
                view.DefaultView = true;
                view.Update();
                list.Update();
            }
        }

Your loop will be similar to

public static void LoopSites(string siteURL, string listName)
{
 using(SPWeb web = new SPSite(siteURL).OpenWeb())
 {
   SPList spList = web.Lists.TryGetList(listName);
   if(spList != null)
   {
     CreateView(splist);
     SetDefaultView(SPList list);
   }
   SPWebCollection collWebSite = web.webs;
   foreach(SPWeb sub in collWebSite)
   {
    LoopSites(subSite.Url, listName);
    subSite.Close();
   }
 }
}

If you need to this happen to all future Document Libraries then I would also recommend creating a feature with a (ListAdded) event receiver that attaches to all lists of the type you wish to have the new view on and set default. This will need to be activated on every web.

Luckily I had the code for the Console App. You are own your own for the Feature Event Receiver, but it would use the CreateView and SetDefaultView methods.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.