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 - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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