Wednesday 5 June 2013

How to add a SharePoint List field programmatically

How to add a SharePoint List field programmatically

Microsoft SharePoint is very customizable and although you probably won’t have any reason to do this outside of the SharePoint UI, 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 for adding a field to many different SharePoint lists and/or libraries.

Code to add a new SharePoint list column

01.private void button1_Click(object sender, EventArgs e)
02.{
03.    //add a new custom field type
04.    using (SPSite sps = new SPSite("http://YourSiteUrl"))
05.    {
06.        using (SPWeb spw = sps.OpenWeb())
07.        {
08.            SPList spl = spw.Lists["TestList"];
09.            String strNewField = "<Field "
10.                "Type='Text' "
11.                "Hidden='FALSE' " +
12.                "DisplayName='MyNewField' " +
13.                "ResultType='Text' " +
14.                "ReadOnly='False' " +
15.                "Name='MyNewField'></Field>";
16.                          
17.            try
18.            {
19.                spl.Fields.AddFieldAsXml(strNewField);
20.            }
21.            catch (SPException ex)
22.            {
23.                // Notify error that a duplicate name was detected
24.                textBox1.Text += ex.ToString();
25.            }
26.            spl.Update();
27.        }
28.    }
29.}
 

Delegating elevated priviledges to your SharePoint method

try
{
 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
  using (SPSite site = new SPSite(properties.WebUrl))
  {
   using (SPWeb web = site.OpenWeb())
   {
    //do code
   }
  }
 });
}
catch (Exception ex)
{
 //
}

No comments:

Post a Comment