Search code examples
visual-studio-2008sharepoint-2007mosswss-3.0

WSS3 - setting a default value on a SPFieldType.DateTime after creation


I'm using WSS3 and C# to create site and I am creating a class to change fields on lists after they have been created. I have already created an SPField.DateTime type with no default value, but after upgrade I need the default is one week, ie if today is 4/4/2012 the default date will have to be 11/4/2012. My current code that does not work follows:

//web is already defined as the current web
lista.Fields["Fecha de Caducidad de la Noticia"].DefaultValue = DateTime.Today.AddDayss(7).ToString("d/m/yyyy");
lista.Fields["Fecha de Caducidad de la Noticia"].Update();


Solution

  • Try DefaultFormula:

    SPField field = lista.Fields["Fecha de Caducidad de la Noticia"]
    field.DefaultFormula = "=[Today]+7";
    field.Update();
    

    Also, the use of the field variable is important. It is not just a matter of convenience. Item collections in SharePoint are often reloaded each time they are called. So calling lista.Fields["Fecha de Caducidad de la Noticia"].Update() might only update a new, unchanged version of the field.