Home > Blogs > Blog Post

Code Sample : How to add a site column to a list

by Mark Jones | Dec 09, 2011

This code sample illustrates how to add an existing SharePoint site column (SPField) to a SharePoint list (SPList).

public static string AddFieldToList(SPWeb web, string listName, 
 string fieldName, SPFieldType fieldType,
 bool fieldRequired)
{
    LogHelper.LogDebug(logger, "Begin AddFieldToList");
 
 string internalListName = string.Empty;
 
    ValidationHelper.VerifyStringArgument(listName, "listName");
 
    SPList list = web.Lists[listName];
 
 if (list != null)
    {
        internalListName = AddFieldToList(web, list, fieldName, fieldType, fieldRequired);
    }
 
    LogHelper.LogDebug(logger, "End AddFieldToList");
 return internalListName;
}
 

 

public static string AddFieldToList(SPWeb web, SPList list, string fieldName, 
                                    SPFieldType fieldType, bool fieldRequired)
{
    LogHelper.LogDebug(logger, "Begin AddFieldToList");
 
    ValidationHelper.VerifyObjectArgument(web, "web");
    ValidationHelper.VerifyObjectArgument(list, "list");
    ValidationHelper.VerifyStringArgument(fieldName, "fieldName");
 
 string internalFieldName;
 
 try
    {
        SPFieldCollection lstFields = list.Fields;
 if (lstFields.ContainsField(fieldName))
        {
 throw new SafException("Field Name:" + fieldName +
 " already exist in the list:" +
                                    list.Title);
        }
 
        internalFieldName = lstFields.Add(fieldName, fieldType, fieldRequired);
    }
 catch (Exception ex)
    {
        LogHelper.LogError(logger, "SPListHelper", "AddFieldToList", ex);
 throw;
    }
 finally
    {
        LogHelper.LogDebug(logger, "End AddFieldToList");
    }
 
 return internalFieldName;
}

Compliance using DocRead

DocRead logoDocRead for SharePoint can help you manage policy compliance by:

  • Targeting documents or policies at specific groups of users
  • Allowing a specific amount of time for users to confirm agreement 
  • Sending email reminders when policy compliance is overdue
  • Users self-certify that they have read and fully understood the policy details
  • Securely storing records of confirmed policy acceptance
  • Monitoring the user acceptance of policies via a reporting suite
  • Providing detailed reading reports and statistics
  • Report drill through to show who has not accepted the policy
  • Automatically sending historic compliance tasks and policies to new users when they are added to a group
  • Bringing policy compliance requests immediately to users attention when they log on

DocRead is simple to install and configure. It seamlessly integrates with SharePoint and can be added to any existing SharePoint site.

To find out more, visit the DocRead product site.


blog comments powered by Disqus