Tuesday, May 18, 2010

Creating a SharePoint List programmatically using the object model

Creating a SharePoint List programmatically using the object model

There are two ways to create a SharePoint list programmatically

1. Creating a List programmatically by using out of the box List Template Types, there are many OOTB list templates are available in the SharePoint, list of some of them is geven below.
You can create a list by picking one of the List Template Types available in the SPListTemplateType object

SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", SPListTemplateType.GenericList);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();

OOTB List Templates


Events
Contacts
Tasks
PictureLibrary
DiscussionBoard
Survey
DocumentLibrary
Links
Document Library
Announcements
GenericList
WorkflowHistory
DataConnectionLibrary
DataSources
GanttTasks
CustomGrid
NoCodeWorkflows
XMLForm
WebPageLibrary
WorkflowProcess
Form Library
wiki
Wiki Page Library
Picture Library
Picture
Contacts
Calendar
Discussion Board
Project Tasks
Issue Tracking
Custom List
Custom List in Datasheet View
Survey Survey
Custom Workflow Process
Languages and Translators
Translation Management Library
DataSources
Data Connection Library
Workflow History
No Code Workflows




2. Creating a List programmatically with Custom List Template Types
If you have created your own custom list template, you will need to reference the id by enumerating what List Template Types are available at the Site Collection.


SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;

SPListTemplateCollection listTemplates = site.GetCustomListTemplates(mySite);
SPListTemplate template = listTemplates["Enter template name here"];
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", template);
SPList list = web.Lists[listId];

web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();


There are some otherways also like using Feature etc to create a sharepoint list, which I am going to explain it in my next post.

Thanks
Sanjay Tiwari
Dallas, Texas

No comments: