Поделиться через


Create your own list in SharePoint from a template

So I've tried to create a list from one of my own list templates that I saved. This should be a really simple task barely worthy of a blog post… Or so I thought.

This is what I did:

  1. Create a new list
  2. Fill it with entries
  3. Save the list as a list template (gave it a really good name)

Fired up Visual Studio and started to code (first attempt):

using (SPSite sitecollection = new SPSite(https://moss))
{
    using (SPWeb web = sitecollection.AllWebs["TestSite"])
    {
        SPListTemplateCollection listtempColl = web.ListTemplates;
        SPListTemplate listTemp = listtempColl["MyOwnSavedList"];
        web.Lists.Add("NewlyCreatedList","", listTemp);
        web.Update();
    }
}

Now this didn't work, turns out the web.ListTemplates doesn't return ALL ListTemplates…
If you want to create a list from a template that you have saved yourself you have to fetch those templates using this code instead:

using (SPSite sitecollection = new SPSite(https://moss))
{
    using (SPWeb web = sitecollection.AllWebs["TestSite"])
    {
        SPListTemplateCollection listtempColl = sitecollection.GetCustomListTemplates(web);
        SPListTemplate listTemp = listtempColl["MyOwnSavedList"];
        web.Lists.Add("NewlyCreatedList","", listTemp);
        web.Update();
}
}

Comments