Share via


Creating a read-only field with default value in a SharePoint list

Whenever we create a column with type “Single line of text” in SharePoint lists we will get an option for providing default value. If we provide the default value and once if we add any item to that list with that field , then we can see the default value in a text box in the edit or new form and even we can edit it at that time. So, if we want to create a read-only column with default value and we can’t edit it, then you can implement it by using the FieldAdded event.

FieldAdded event is list specific synchronous event and it will get from SPListEventReciver class. Once you attached the event to a list then whenever you add a new column to the list, this event will fire and we can customize it in this hook point. Below I am giving the detailed steps on how we can accomplish this requirment.

1. Create a class library add SharePoint dlls and the a class with the following code.

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Utilities;

namespace TestEvent

{

class ReadonlyFieldTest : SPListEventReceiver

{

public override void FieldAdded(SPListEventProperties properties)

{

SPField oField = properties.Field;

if (oField.Title == "MyTestColumn")// you can think about a better check point here.

{

oField.DefaultValue = "MyDefaultValue";

oField.ReadOnlyField = true;

oField.Update();

}

}

}

}

2. Deploy the dll in GAC after compiling the class library with a strong name

3. You can register the event handler using a feature or using SharePoint APIs. If you want to register the event handler to a particular site collection or farm level, then you can go with a custom feature. Since I am testing it with only one List, here I have registered FieldAdded event using SharePoint APIs. I have created a .Net console application to do that.

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

namespace EventRegistrationTool

{

class Program

{

static void Main(string[] args)

{

using (SPSite oSite = new SPSite("https://<sitename>"))

{

using (SPWeb oWeb = oSite.OpenWeb())

{

SPList oList = oWeb.Lists["Shared Documents"];

string strAssembly = "TestEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fac0274b1d81d1fd";

string strClass = "TestEvent.ReadonlyFieldTest";

oList.EventReceivers.Add(SPEventReceiverType.FieldAdded,strAssembly,strClass);

oList.EventReceivers.Add(SPEventReceiverType.FieldAdding,strAssembly, strClass);

}

}

}

}

}