Tag Archives: list column

Creating SharePoint list and add column programmatically

In this post we will see two methods for creating SharePoint list programmatically and add column to the created list

Using Object model
[sourcecode language="csharp"]SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb();
SPListTemplate template = web.ListTemplates["Custom List"];
web.AllowUnsafeUpdates = true;
web.Lists.Add("MyList", "This list created using code", template);
SPList mylist = web.Lists["MyList"];
mylist.Fields.Add("MyField", SPFieldType.Text, false);
mylist.Update();
web.AllowUnsafeUpdates = false;[/sourcecode]

Using PowerShell Script

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$SPSite = New-Object Microsoft.SharePoint.SPSite("http://mysite");
$OpenWeb = $SpSite.OpenWeb();
$TemplateType = $OpenWeb.ListTemplates["Custom List"];
$OpenWeb.Lists.Add("my list"," ",$TemplateType);
$list=$Openweb.Lists["my list"]
$list.Fields.Add("My field", "Text", 0)
$OpenWeb.Dispose();
$SPSite.Dispose();[/sourcecode]