Tuesday, October 27, 2009

Update SharePoint List Column Property Programatically

In order to update a list column (field) property in SharePoint, such as the setting of required or not, we can do the change through the column's setting page from the list's setting page. But some field properties don't display in setting page, and you can't make the change via UI.

Can we update a field property programatically? The answer is yes. For those field properties exposed directly to SPField, the update is simple. Following code sets a list column named "CustomField" to be hidden:
        using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyCustomList"];
list.Fields["CustomField"].Hidden = true;
list.Update();
}
}
If the field property is not exposed to a SPField object, we can also make the change by updating the field's schema XML. SPField has a property called "ShowInNewForm" that determines whether the field shows in the NewForm page (the page to create a new list item). Following code demos how to set a site column not to display in NewForm page:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

class Program
{
static void Main(string[] args)
{
TurnOffFieldInNewForm("http://localhost", "My Custom List", "CustomField");
}


static void TurnOffFieldInNewForm(string siteName, string listName, string fieldName)
{
using (SPSite site = new SPSite(siteName))
{
using (SPWeb web = site.OpenWeb("Team"))
{
SPList list = web.Lists[listName];
string origSchemaXml = web.Fields.GetFieldByInternalName(fieldName).SchemaXml;

string schemaXml = origSchemaXml.Replace("ShowInNewForm=\"TRUE\"", "ShowInNewForm=\"FALSE\"");
if (!schemaXml.Contains("ShowInNewForm="))
{
int index = schemaXml.IndexOf("></Field>");
schemaXml = schemaXml.Substring(0, index) + " ShowInNewForm=\"FALSE\"></Field>";
}

web.Fields.GetFieldByInternalName(fieldName).SchemaXml = schemaXml;
list.Fields.GetFieldByInternalName(fieldName).SchemaXml = schemaXml;
list.Update();
web.Update();
}
}
}
}

Note: updating the site column property doesn't have impact on existing lists that are using that site column, and the update only takes effect for new lists or new referencing to that site column. Because the list column copies the site column's schema xml once when it's first created. So we need to update the list column's property in existing lists separately.