Thursday, 4 March 2010

Creating SharePoint Views

As usual a little background, as I do not want you to take it out of context.

I am using SSIS with the SharePoint connectors to extract data out of a SharePoint list, to do so I wanted to create a custom view, this allows me to get all of the columns and to select the rows I need.  Also I like to do these things programmatically as I personally will not be doing the release.

To create a View we need to use SPList.Views.Add, which is slightly unusual because we cannot add an object. see http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spviewcollection.add.aspx

So this is the code I have used.

string viewName = "ExportView";

var strCollViewFields = new StringCollection();

foreach (SPField field in site.Lists[projectsListName].Fields)
{
if (field.Hidden == false)
{
strCollViewFields.Add(field.InternalName);
}
}
var strQuery = "<Where><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Complete</Value></Eq></Where>";


site.Lists[projectsListName].Views.Add(viewName, strCollViewFields, strQuery, 100,true,false, SPViewCollection.SPViewType.Html, false);





The StringCollection is of type System.Collections.Specialized.StringCollection and is a list of the internal field name, this is usually the text on the field. With "_x0020_" instead of spaces.

StrQuery is a CAML query I use CAML Builder (by U2U) but remember to remove the <query> tag, or it will fail and all items will be returned.


100 is the number of rows, when imported this is ignored


true is whether to show pagination.


false is whether this is the default view


The next shows how to display the screen take a look at http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spviewcollection.spviewtype.aspx


And the last is whether this is a personal view or not.

No comments:

Post a Comment