SharePoint 2010 Programmatically Create List from Custom List Template in C#

Wed, Apr 12, 2017 2-minute read

Yep - tech 2010! Continuing my tour of strange facets of old SharePoint technology, here’s something new I tried to do today that took a lot more effort than it should.

The objective was simple: create a new list, based on an existing list.

This is reasonably easy to do using List Templates… when you know how of course.

So the steps are:

  1. Save a copy of your current list as a template
  2. Create a new list based on that template.

The main issue is the way SP stores the custom list template when you’ve created it.

I’ll cut to the chase:

// create the list template
using(var site = new SPSite("http://yoursite")
using(var web = site.OpenWeb())
{
var list = web.TryGetList("Your List Name");
if(null != list)
{
list.SaveAsTemplate("filename","listname",false); // check the docs to know what these params are
}
}

// create new list using it
using(var site = new SPSite("http://yoursite")
using(var web = site.OpenWeb())
{
var templates = site.GetCustomListTemplates(web); // this is the kicker... 
var tpl = templates["listtname"]; // whatever you called it above
web.Lists.Add("your new list name", "some description", tpl);
}

It’s loading the Custom List Templates from a method on the site object that caught me out.

As a kicker, if you want to delete a custom list template, then you actually need to do this via the List Templates Gallery:

using(var site = ...) // etc

var list = web.TryGetList("List Template Gallery");
if(null != list)
{
foreach(SPListItem obj in list...) // etc
if(obj.Name == "your template name")
{
obj.Delete();
list.Update();
}
}

Hope this helps.