How to Create Site Columns Programmatically in SharePoint?

Requirement: Add Site columns to the SharePoint site programmatically as part of a site provisioning code.

Add a New Site column to SharePoint Site Programmatically:  

using (SPSite site = new SPSite("http://sharepoint.com"))
{
   SPWeb web = site.RootWeb;
   
	//Add Site Column

   //Add choice Field "Operating Country"
   if (!web.Fields.ContainsField("Operating Country"))
   {
		string countryField=web.Fields.Add("Operating Country", SPFieldType.Choice , false);

		//Set the Field Properties
		SPFieldChoice OperatingCountry = (SPFieldChoice)web.Fields.GetField("Operating Country");

		//Set the group for the Site column
		OperatingCountry.Group = "Crescent";

		//Add the choices
		string[] countries = new string[] { "Germany", "Japan", "Romania", "Switzerland", "United States" };
		OperatingCountry.Choices.AddRange(countries);

		//Set the default value
		OperatingCountry.DefaultValue = "United States";

		//Set Fillable value
		OperatingCountry.FillInChoice = true;

		//Update the field
		OperatingCountry.Update();
   }
}

Create SharePoint site column programmatically with C# Object Model code:

Alternate Approach:

namespace CreateSiteColumns
{
    class Program
    {
        static void Main(string[] args)
        {
           using (SPSite oSPSite = new SPSite("http://SharePoint.com"))
            {
                using (SPWeb oSPWeb = oSPSite.RootWeb)
                {
                    //Method 1
                    oSPWeb.Fields.Add("bptSalary1", SPFieldType.Currency, true);
                    oSPWeb.Update();

                    //Method 2
                    string SalaryField2 = oSPWeb.Fields.Add("bpt-Salary2", SPFieldType.Currency, false);

                   //Set the Properties
                    SPFieldCurrency bptSalary2 = (SPFieldCurrency)oSPWeb.Fields.GetFieldByInternalName(SalaryField2);

                    bptSalary2.Group = "BPT Site columns";
                    bptSalary2.DisplayFormat = SPNumberFormatTypes.TwoDecimals;
                    bptSalary2.MinimumValue = 0;
                    bptSalary2.Update();

                    //Method 3 using Field schema
                    string bptSalary3 = "<Field Type=\"Number\" DisplayName=\"Bpt-InvoiceNum\" Required=\"TRUE\" EnforceUniqueValues=\"FALSE\" Indexed=\"FALSE\" Min=\"1\" Max=\"10000\" Group=\"Bpt Columns\" ID=\"{b81c7da6-1317-46fa-a32b-9f446c30b6e9}\" SourceID=\"{03548e22-e4b5-4ae0-b325-12c584754e72}\" StaticName=\"Bpt-InvoiceNo\" Name=\"Bpt-InvoiceNo\"></Field>";

                    // Call the SharePoint method to create the field.
                    oSPWeb.Fields.AddFieldAsXml(bptSalary3);
                    oSPWeb.Update();
                }
            }
        }
    }
}

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

Leave a Reply