Archive for June 20, 2012

Adding Lists Programmatically based on a custom ListTemplate

When adding Lists programmatically, it’s most likely we use the Lists.Add() Methods. These Methods are giving us choice on how to create the list. In my case I wanted to use a custom ListTemplate which is inside a custom Feature.

Feature Activation

First I chose to get my custom SPListTemplate from the Web and use the Add(String, String, SPListTemplate) Method. But I figured I had to activate the Feature that has the Template in it so I can retrieve it from the SPWeb. Now I didn’t want to do that because there was a whole lot of templates and declarative lists inside I didn’t want to use.
 

Solution

When I came across the last override of this Method Add(String, String, String, String, Int32, String, String, SPFeatureDefinition, SPListTemplate.QuickLaunchOptions). It didn’t say anything about the Feature needed activation. I tried it and so it seemed. The List is Created based on the correct Template and the Feature that hosts the Template stays inactive.

Example

The call I now use to create my custom List is:

Guid discListId = web.Lists.Add(“My Discussions”, “Forum for community discussions”, “Lists/Discussions”, “feature id as string”, Template ID, “100”);

Summary

While this is not a very common scenario, there might be some cases where you need just that ListTemplate from an installed Feature which you don’t want to activate for that Site(Collection). It’s good to know this way of adding a SPList programmatically give you the chance to do so.