Creating List Using List Definition Programatically

n

n
n

n
n

nLet’s have a look at how we can create custom list by using our own List Definition

n

nThere is <ListTemplate> element using which we can easily create our own list definition.          Andrew Connel has explained this very well in this post

n

nBut this is something different approach I wanted to use with our own list definitions

n

nAfter creating List Definition I didn’t want to add List Instance to the solution because if we do so, then it creates a list with based definition automatically when feature gets activated.

n

nI wanted to have a control over creation of this list which will be based on our custom List Definition. Which puzzled me..

n

nThen I found a way to achieve this by using object model.. I don’t know yet If there are multiple ways to do this but this one was perfect choice for me and worked very well J

n

nWhen we create a List Definition then we have a feature which provisions list definition

n

nNote that GUID used here in code is Feature Id of the feature which provisions the list definition.

n

nAlso : please take into consideration that there are some methods in server object model available for creating a list using list templates directly , but this was something different than list templates, so this approach was preferred , because List Templates are stored into the content database while list definitions resides on actual file system of the server

n

try

n

n{

n

n

n  SPList list = null;

n

n  using (SPSite site = new SPSite(“http://yoursite/”))

n

n  {

n

n     using (SPWeb web = site.RootWeb)

n

n     {

n

n      //List Will be Created Based on this ListDefinition

n

n– OOB Custom List Definition

n

n      //00BFEA71-DE22-43B2-A848-C05709900100

n

n

n

n        foreach (SPList _list in web.Lists)

n

n        {

n

n          if (_list.Title.Equals(“TestList”))

n

n          {

n

n              list = _list;

n

n          }

n

n        }

n

n

n

n        if (list == null)

n

n        {

n

n         web.AllowUnsafeUpdates = true;

n

n         Guid listID = web.Lists.Add(“TestList”, //List Title

n

n                      “This is Test List”,      //List Description

n

n                      “Lists/TestList”,         //List Url

n

n                      “00BFEA71-DE22-43B2-A848-C05709900100”, //Feature Id of List definition Provisioning Feature – CustomList Feature Id

n

n                      100,                     //List Template Type

n

n                     “101”);      //Document Template Type .. 101 is for None

n

n

n

n           web.Update();

n

n           web.AllowUnsafeUpdates = false;

n

n                           

n

n         }

n

n        }

n

n

n

n

n

n     }

n

n    }

n

n    catch (Exception ex)

n

n    {

n

n      

n

n    }

n
nthis is the way to do this and works fine 🙂
nI hope some one finds this useful..

Leave a Comment