Search code examples
sharepointsharepoint-list

Adding new column to sharepoint list with default value for old items


I have added a new Boolean column to my sharepoint list. Although I have set the default value for the column but the existing items have no value for the new column.

if (!FieldUtilities.FieldExists(calculationList, M56CalculationFields.INN_M56_IsNewItem))
{
    calculationList.Fields.Add(M56CalculationFields.INN_M56_IsNewItem, SPFieldType.Boolean, false);
    var isNewItem = (SPFieldBoolean)calculationList.Fields[M56CalculationFields.INN_M56_IsNewItem];
    isNewItem.Group = "MMC";
    isNewItem.Title = "Is NewItem";
    isNewItem.Description = "Is New Item";
    isNewItem.ShowInEditForm = false;
    isNewItem.DefaultValue = "0";
    isNewItem.Update();
    calculationList.Update();

}

How can I add the default value for the existing items?


Solution

  • What you need to do is iterate through the items in your list (look for items with null values, if that's what your intention is) and set each field in the item to the default value. It would look something like this:

    var query = new SPQuery();
    query.Query = @"<Where><IsNull><FieldRef Name='MyField' /></IsNull></Where>
    
    var items = calculationList.GetItems(query);
    foreach(SPListItem item in items)
    {
       item["MyField"] = "Default Value";
    }
    

    You need to do this for each field. I hope this helps!