How to add a SharePoint List field programmatically

You probably won’t have any reason to do this outside of the SharePoint UI, but it can be helpful if you have a number of lists you want to add a column (field) to. This little piece of code can come in handy.


        private void button1_Click(object sender, EventArgs e)
        {
            //add a new custom field type
            using (SPSite sps = new SPSite("http://YourSiteUrl"))
            {
                using (SPWeb spw = sps.OpenWeb())
                {
                    SPList spl = spw.Lists["TestList"];
                    String strNewField = "<Field " +
                    	"Type=\"Text\" " +
                    	"Hidden=\"FALSE\" " +
                    	"DisplayName=\"MyNewField\" " +
                    	"ResultType=\"Text\" " +
                    	"ReadOnly=\"False\" " +
                    	"Name=\"MyNewField\"></Field>";

                    try
                    {
                        spl.Fields.AddFieldAsXml(strNewField);
                    }
                    catch (SPException ex)
                    {
                        // Notify error that a duplicate name was detected
                        textBox1.Text += ex.ToString();
                    }
                    spl.Update();
                }
            }
        }

Hope this helps.

.advertisement

Leave a Reply