Create sharepoint list programatically

Here is a sample code to create a sharepoint list programatically. It adds two columns, one normal column and another lookup column.

_site = new SPSite(AppConfig.SiteUrl);
_web = _site.OpenWeb(AppConfig.WebUrl);
_web.Lists.Add("Clientes", "", SPListTemplateType.GenericList);      
SPList list = _web.Lists["Clientes"];

//Add normal column
list.Fields.Add("Nome", SPFieldType.Text, true);

//Add lookup column
SPList marcoList = _web.Lists["Marco"];
list.Fields.AddLookup("Marco", marcoList.ID, true);
SPFieldLookup marcoColumn = (SPFieldLookup)list.Fields["Marco"];
marcoColumn.LookupField = marcoList.Fields["Title"].InternalName;
marcoColumn.Update();

//Actualize default view
SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add("Nome");
defaultView.ViewFields.Add("Marco");
defaultView.Update();

No comments:

Post a Comment