Wednesday, March 21, 2012

CreateField with Default Value

public static void CreateFieldWithDefault(SPList list, string fieldName, string defaultValue, SPFieldType spFieldType)
{
try
{
string fieldNameNoSpaces = TrimSpaces(fieldName);
string displayName = list.Fields.Add(fieldNameNoSpaces, spFieldType, false);
SPField field = list.Fields[fieldNameNoSpaces];
field.Title = fieldName;
if (spFieldType != SPFieldType.Boolean)
{
field.DefaultValue = defaultValue;
}
field.Update();
if (spFieldType == SPFieldType.DateTime)
{
SPFieldDateTime dt = (SPFieldDateTime)field;
dt.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
dt.Update();
}
SPView view = list.DefaultView;
view.ViewFields.Add(fieldName);
view.Update();
}
catch (Exception ex)
{
Logging.LogException("CreateFieldWithDefault", ex);
}
}

private static string TrimSpaces(string fieldName)
{
string[] names = fieldName.Split(' ');
string fieldNameNoSpaces = string.Empty;
foreach (string name in names)
{
fieldNameNoSpaces += name;
}
return fieldNameNoSpaces;
}

No comments:

Post a Comment