Thursday, June 18, 2009

Add Custom Column Choice to sharepoint List

This code can help you create custom column on List.
Create a custom Choice field call Year and multiple years choice and add to List.

using (SPSite site=new SPSite("Site Path"))
using (SPWeb web=site.OpenWeb())
//Validate Field is exist
if (!web.Lists["Shared Documents"].Fields.ContainsField("Year"))

SPField customField;
//Creating a new field
MyField = web.Fields.CreateNewField(SPFieldType.Choice.ToString(), "Year");
//Field as required
MyField.Required = true;
SPList list = web.Lists["Shared Documents"];
SPField Year = MyField;

SPFieldChoice YearField = (SPFieldChoice)list.Fields["Year"];
for (int i = 1990; i < 2021; i++)
YearField.DefaultValue = DateTime.Now.Date.Year.ToString();

Hope you like...

No comments: