Adis Jugo

The Southern Side – SharePoint thoughts and bytes // SharePoint MVP

Change the fields order in the SharePoint View programmatically

I was asked today how to change the order of the fields programmatically in the SharePoint view (SPView). Since there is no “position” or “order” property, and since the “ViewFields” property returns a “SPViewFieldCollection”, which is not much more than a StringCollection, it’s not that straight-forward.

The easiest way is to accomplish this is to empty the ViewFields property of the current View, sort the fields as you would like to have it, and add it again, one by one, to the ViewFields.

The following code snippet moves the field “Test” to the first position in all the Views except the “Explorer View”.


//iterate all the views
int viewsCount = yourLibrary.Views.Count;
for (int i = 0; i < viewsCount; i++ )
{
SPView view = yourLibrary.Views[i];

if (view.Title != "Explorer View")
{

StringCollection oldFields =
view.ViewFields.ToStringCollection();

//clear all fields
view.ViewFields.DeleteAll();

//add wanted field
view.ViewFields.Add(yourLibrary.Fields["test"]);

//add orher fields
foreach (string fieldName in oldFields)
{
if (fieldName != "test")
{
if (yourLibrary.Fields.ContainsField(fieldName))
view.ViewFields.Add(fieldName);
}

}

view.Update();

yourLibrary.Update();
}
}

Sun, January 30 2011 » Development

Share 'Change the fields order in the SharePoint View programmatically' on Facebook Share 'Change the fields order in the SharePoint View programmatically' on Twitter Share 'Change the fields order in the SharePoint View programmatically' on LinkedIn Share 'Change the fields order in the SharePoint View programmatically' on XING

Comments

awesome comments!

Login