How to programmatically add a field to all views in a SharePoint list
Today I had a need to add a new field to multiple lists each with multiple views and to group by the new column in each of the views. There were about 6 lists and 12 or so views on each list and doing this through the interface, although possible, would have been tedious, error prone and very boring (especially for the client since he was doing it). So I decided to automate the process. I added the field to each of the lists manually, although I could have automated that too :). I then wrote a simple console application that accepts a few parameters, namely the new fields internal name, the site collection URL, the web path, the list or library name, the position of the field, whether or not to group by that field, and whether or not to collapse the groups (if grouped).
Here is the main function. I have a few helper functions that gather input but this is the meat an potatoes.
static void Main(string args)
// if all input is valid then proceed
if (true == GatherInput())
// get a reference to the site collection
using (SPSite site = new SPSite(siteUrl))
// get a reference to the site
using (SPWeb web = site.OpenWeb(webPath))
// get a reference to the list or library
SPList list = web.Lists[listLibName];
// iterate though all the views in a list
for (int i = 0; i <= list.Views.Count - 1; i++)
// get a reference to a view
SPView view = list.Views[i];
// only do this for visible views and ignore the useless explorer view :)
if (view.Hidden == false && !(view.Title == "Explorer View"))
// retrieve the names of all of the fields used in the view
StringCollection viewFields = view.ViewFields.ToStringCollection();
// remove all of the fields from the view
// create the new field to insert
SPField newField = new SPField(list.Fields, newFieldName);
// add each of the fields back into the view
// while adding the new field at the desired location
for (int k = 0; k < viewFields.Count; k++)
SPField field = new SPField(list.Fields, viewFields[k]);
if (k == Convert.ToInt32(fieldOrdinal))
if (true == groupByField)
// group by the new column, collapsing the group if necessary
string query = string.Empty;
query += "<GroupBy Collapse=\""
if (true == collapseGroup)
query += "TRUE"
query += "FALSE"
query += "\">"
query += "<FieldRef Name=\"" + newField.InternalName + "\" />"
query += "</GroupBy>"
view.Query += query;
// update the view
site.RootWeb.Dispose(); //this was opened implicitly when we referenced SPSite and needs to be disposed.