This example shows how to create and add a new view to a list. In this case it's a document library of MySite to which the view is added. The view displays all the Word documents in the document library.
private void CustomizeDocLibViews(SPSite mysite)
{
SPDocumentLibrary docs = GetDocLib(mysite);
string[] docExtensionsWord = new string[] { ".doc", ".docx", ".dot", ".dotx" };
AddDocumentLibraryExtensionView(docs, "Word Documents", docExtensionsWord);
}
private static SPDocumentLibrary GetDocLib(SPSite mysite)
{
SPDocumentLibrary docs = null;
try
{
docs = (SPDocumentLibrary)mysite.RootWeb.Lists["Personal Documents"];
// SPList documentLibraryList = mysite.GetCatalog(SPListTemplateType.DocumentLibrary);
// returns Personal Documents, but what about shared documents?
}
catch (ArgumentException argEx)
{
// list does not exist
}
return docs;
}
private void AddDocumentLibraryExtensionView(SPDocumentLibrary docs, string viewName, string[] extensions)
{
try
{
if (docs != null)
{
SPView tmp = docs.Views[viewName];
}
}
catch (Exception e)
{
// view does not exist
//instantiate the viewcollection of the current documentlibrary
SPViewCollection colViews = docs.Views;
//Define query
string query = "<OrderBy>";
query += "<FieldRef Name=\"FileLeafRef\"/>";
query += "</OrderBy>";
query += "<Where>";
query += "<Or>";
foreach (string extension in extensions)
{
query += "<Contains><FieldRef Name=\"FileLeafRef\"/><Value Type=\"File\">" + extension + "</Value></Contains>";
}
query += "</Or>";
query += "</Where>";
//Define which columns should be shown on screen in the result
StringCollection collViewFields = null;
try
{
//columns of an existing view
collViewFields = docs.Views["All Items"].ViewFields.ToStringCollection();
//or define your own:
//StringCollection collViewFields = new StringCollection();
//collViewFields.Add("Column1");
//collViewFields.Add("Column2");
}
catch
{
collViewFields = new StringCollection();
collViewFields.Add("LinkFilename");
}
//Add the view
colViews.Add(viewName, collViewFields, query, 100, true, false);
// Add the view Based on an existing view
//collViews.Add(strViewName, oList.Views["All Items"].ViewFields.ToStringCollection(), strQuery, 100, true, false);
//Add the view as a HTML View instead of a Grid View
//collViews.Add(strViewName, collViewFields, strQuery, 100, true, false , Microsoft.SharePoint.SPViewCollection.SPViewType.Html, False)
}
catch
{ }
}