Interview Questions administrator

Best SharePoint administrator Interview Questions and Answers with topic wise:


Recycle Bin | MMS | ManagedVsCrawledProperties |

Wednesday, February 22, 2012

Add Columns / Fields Programmatically to a SharePoint List

Before adding column(field) to the specified list it’s better to check whether that lists exists or not and new created field already exists or not? In my code, I am checking all these conditions.

Refer Also:
  1. How to create a list programmatically?
  2. How to check if the lists exits ornot?
  3. How to check if the list templateexists or not?
  4. Error handling technique:

#region AddColumn
 /// 
 /// FUNCTION        : AddColumn
 /// PURPOSE         : Add the OpenInNewWindow column to list
 /// PARAMETERS      : currentWeb -> current web
 /// listName -> A string containing the list name
 /// RETURNS         : The result as a Void
 /// -------------------------------------------------------------------------
/// 
 public const string CustomFieldName = "CustomField";
 public static void AddColumn(SPWeb currentWeb, string listName)
 {
  try
  {
   using (currentWeb)
   {
    if (IsListExists(listName, currentWeb))
    {
     SPList currentList = currentWeb.Lists[listName];
     currentWeb.AllowUnsafeUpdates = true;
     if (!currentList.Fields.ContainsField(CustomFieldName) && currentWeb.AvailableFields.ContainsField(CustomFieldName))
     {
       currentList.Fields.Add(currentWeb.AvailableFields[CustomFieldName]);
       currentList.Update(); 
       SPView view = currentList.DefaultView;
       view.ViewFields.Add(CustomFieldName);
       view.Update();                            
     }
     SPListItemCollection lstItemColl = currentList.Items;
     //To add value to the custom field
     if (lstItemColl.Count > 0)
     {
       foreach (SPListItem lstItem in lstItemColl)
       {
         lstItem[CustomFieldName] = "No";
         lstItem.Update();
      }
    }
   currentWeb.AllowUnsafeUpdates = false;
  }
 }
}
 catch (Exception ex)
 {
  //Error handle Code
 }
}
#endregion

No comments:

Post a Comment