Wednesday, April 18, 2007

Creating a document library with a view with grouping in MOSS programmatically

For this project I'm on at the moment, a document library needed to be created programmatically. It needed a view and inside the view, a grouping had to be made.

To do this, I found some info on the various steps on some blogs, msdn, ... but I hardly found anything about grouping. This is why I thought it would be useful to post a code example of the whole thing: creating a document library, creating a view on it and creating a grouping.

The code is fairly simple once you know it, so I won't go any deeper into it. If you've got any questions though, feel free to ask!

WebToAddLibraryTo.AllowUnsafeUpdates = true;

SPListTemplate listTemplate = WebToAddLibraryTo.ListTemplates["Document Library"];

System.Guid guidLib = WebToAddLibraryTo.Lists.Add("Title", "Description", listTemplate);
WebToAddLibraryTo.Update();

SPList docLib = WebToAddLibraryTo.Lists[guidLib];

docLib.EnableVersioning = true;
docLib.EnableMinorVersions = true;
docLib.OnQuickLaunch = true;

docLib.Fields.Add("Field name", SPFieldType.Text, true);
docLib.Fields.Add("Another field name", SPFieldType.Text, false);
docLib.Fields.Add("Date field", SPFieldType.DateTime, false);
StringCollection resultStrings = new StringCollection();
resultStrings.Add("Positive");
resultStrings.Add("Negative");
docLib.Fields.Add("Result", SPFieldType.Choice, false, false, resultStrings);

StringCollection viewFieldCollection = new StringCollection();

viewFieldCollection.Add("DocIcon");
viewFieldCollection.Add("LinkFilename");
viewFieldCollection.Add("Another field name");
viewFieldCollection.Add("Date field");
viewFieldCollection.Add("Result");

string defaultQuery ="<GroupBy Collapse=\"TRUE\" GroupLimit=\"100\">" +
"<FieldRef Name=\"Field name\">" +
"<FieldRef Name=\"ContentType\">" +
"</GroupBy>" +
"<OrderBy>" +
"<FieldRef Name=\"LinkFileName\">" +
"</OrderBy>";


Guid oldViewId = docLib.DefaultView.ID;
docLib.Views.Delete(oldViewId);

SPView newView = docLib.Views.Add("New view", viewFieldCollection, defaultQuery, 100, true, true, SPViewCollection.SPViewType.Html, false);

docLib.DefaultView.Update();

docLib.Update();