It is very easy to add a column in a SharePoint List from website front-end, we just need to click "List Settings -> Create Column" and enter the title and type of the field, and click "OK" button. That's it, new field is created.
But what if we have a requirement to add a field in the List programatically. Is it possible?
Yes, It is possible. Refer following code snippet:
using (SPSite site = new SPSite("SiteURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
//Following statement will add the the new column "NewField" in the List
string strFieldName = list.Fields.Add("NewField", SPFieldType.Text, false, false, null);
list.Update();
}
}
Now If we need to create a ReadOnly field, refer following code snippet:
using (SPSite site = new SPSite("SiteURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
//Following statement will add the the new column "NewField" in the List
string strFieldName = list.Fields.Add("NewField", SPFieldType.Text, false, false, null);
list.Update();
SPField field = list.Fields.GetFieldByInternalName(strFieldName);
field.ReadOnlyField = true;
field.Update();
}
}
Recommended readings:
Explore SPList.Fields.Add Method:
http://msdn.microsoft.com/en-us/library/aa540133.aspx
Explore SPFieldType Enumeration:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldtype.aspx
Explore SPField Class:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfield.aspx