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(""))
   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" };

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

		//Set Fillable value
		OperatingCountry.FillInChoice = true;

		//Update the field

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(""))
                using (SPWeb oSPWeb = oSPSite.RootWeb)
                    //Method 1
                    oSPWeb.Fields.Add("bptSalary1", SPFieldType.Currency, true);

                    //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;

                    //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.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *