Tuesday, March 22, 2011

How to create a List in SharePoint 2010?

There are different ways you can create list in SharePoint 2010.
1. By using feature, you can create list by using the ListInstance
<ListInstance
TemplateType="105"
FeatureId="00bfea71-7e6d-4186-9ba8-c047ac750105"
Title="Customers"
Description="Wingtip customers list "
Url="Lists/Customers"
OnQuickLaunch="TRUE" >
</ListInstance>

Please replace [ with < or > according to the match opened tag.

2. By code using Visual Studio 2010
Visual Studio 2010 provides SharePoint projects with a dedicated SharePoint project item template for creating a ListInstance element

SPWeb site = SPContext.Current.Web;
string ListTitle = "ListName";
string ListDescription = "List Description";
Guid ListId = site.Lists.Add(ListTitle, ListDescription, SPListTemplateType.Contacts);
SPList list = site.Lists[ListId];
list.OnQuickLaunch = true;
list.Update();

Then the question is which approach you will select to create the list ?

The one disadvantages of creating list using feature is there is no way to handle name conflicts.
suppose that a user attempts to activate a feature with the ListInstance element in a site that already contains a list with the same title. The feature activates successfully, but the feature’s attempt to create the list silently fails due to the conflict, leaving the functionality of the feature in a unpredictable state.

But you have more control oper creating list using programmatically using SharePoint 2010 object model. Programmatically you can check where the list name same as the name is already exists or not. like

SPWeb site = SPContext.Current.Web;
string ListTitle = "ListName";
string ListDescription = "List Description";
// delete ListName list if it exists
SPList list = site.Lists.TryGetList("Customers");
if (list != null)
list.Delete();
// create new ListName list
Guid ListId = site.Lists.Add(ListTitle, ListDescription, SPListTemplateType.Contacts);
list = site.Lists[ListId];
list.OnQuickLaunch = true;
list.Update();

Another advantage is using code to create lists over the declarative ListInstance element is that you have more control over configuring list properties.
Below is an example for setting the configuration properties.

SPWeb site = SPContext.Current.Web;
string ListTitle = "ListName";
string ListDescription = "List Description";
Guid ListId = site.Lists.Add(ListTitle, ListDescription, SPListTemplateType.Contacts);
list = site.Lists[ListId];
list.OnQuickLaunch = true;
list.EnableAttachments = false;
list.EnableFolderCreation = false;
list.DisableGridEditing = true;
list.EnableVersioning = true;
list.MajorVersionLimit = 3;
list.ReadSecurity = 2;
list.WriteSecurity = 2;
list.Update();

2,3,4 are security properties.