Friday, 30 August 2013

Create list programmatically using SharePoint object model

Below is the code to create list programmatically using SharePoint object model.

using (SPSite site = new SPSite("http://Site URL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = null;
string listName = "MyCustomList";

// Check whether the list already exists
try
{
list = web.Lists[listName];
}
catch (Exception ex)
{
}
---->
if (list == null)
{
Guid listId = web.Lists.Add(listName, "Our Custom List", SPListTemplateType.GenericList);
list = web.Lists[listId];
list.OnQuickLaunch = true;
list.Update();
}
}
}

The above code will create a generic list without any extra field. And it will show in Quick Launch.

You can also add custom columns like below:

list.Fields.Add("FirstName", SPFieldType.Text, true);
list.Update();

No comments:

Post a Comment