Wednesday, May 21, 2014

Creating columns programmatically in SharePoint 2010 / Code to create columns programmatically in SharePoint 2010

try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       using (SPSite osite = new SPSite("http://myserver02:7676"))
                       {
                           using (SPWeb oweb = osite.OpenWeb())
                           {
                               string columnName = "Test";
                               string columnType = "Single line of text";

                               if (columnType.Equals("Single line of text"))
                                   oweb.Fields.Add(columnName, SPFieldType.Text, false);
                               if (columnType.Equals("Date and Time"))
                                   oweb.Fields.Add(columnName, SPFieldType.DateTime, false);
                               if (columnType.Equals("Choice"))
                                   oweb.Fields.Add(columnName, SPFieldType.Choice, false);
                               oweb.Update();
                           }
                       }
                   });

            }

            catch (Exception ex)
            {
               
            }


Now you can navigate to Site Settings -> Galleries ->Site Columns
In this list look for Custom Coloumns Heading in which you would be able to find your column
Tada ! 
Additional Logic Advice : what you can do is,create and xml with the column names and column types and read this xml and create columns programmatically 
Happy SharePointing :) 

No comments:

Post a Comment