How to Create SharePoint ReadOnly Site Columns?

In this post I will show how to create a SharePoint readonly site column with following characteristics:

  1. Site column when added to a list or library should not be editable through UI (even datasheet view)
  2. Users should be able to add list columns based on site column to personal or shared list views of that list
  3. Users should not be able to modify any settings of the list column based on this site column (depends on field type and priviliges).
  4. Any updates to list column values can only be done programmatically

Long story short, I noticed that InfoPath promoted properties which are not editable have all these characteristics. So, I created site column defintion similar to one that is generated automatically for site columns based on an InfoPath form's readonly promoted property.

Here is a sample readonly site column definition:

<

Field ID="{102ED08D-CE13-4f56-B07E-7B5118191949}" Type="Text" Name="ReadonlyTest1" DisplayName="Read Only Test 1" StaticName="ReadonlyTest1" Group="Test Columns" Hidden="FALSE" ReadOnly="TRUE" Required="FALSE" ShowInDisplayForm="TRUE" ShowInViewForms="TRUE" PITarget="" PrimaryPITarget="" PIAttribute="" PrimaryPIAttribute="" Node=""/>

Essentially, add these attributes to any site column definition to make it readonly:

Hidden="FALSE" ReadOnly="TRUE" Required="FALSE" PITarget="" PrimaryPITarget="" PIAttribute="" PrimaryPIAttribute="" Node=""

Following is a sample code to modify the value of list column based on above sample site column when it's added to a custom list called "Test":

using (SPSite site = new SPSite("http://<your site>/"))

{

using (SPWeb web = site.RootWeb)

{

SPList oList = web.Lists["Test"];

SPListItem oListItem = oList.Items[0];

oListItem[

"Read Only Test 1"] = "Updated Text";

oListItem.Update();

}

}