简体   繁体   中英

How do I create a Sharepoint list via a feature receiver and an existing list template

I have a list template in a MOSS List Template Gallery and I need to create a list using this template from a feature receiver. This sounds really easy but I cannot find a way of doing this.

SPWeb has a GetCatalog method that returns an SPList with 1 item - my template - but it is an SPListItem and I need an SPListTemplate. How can I 'convert' the item to the correct type?

Thanks

Use the GetCustomListTemplates method of the SPSite object to get the SPListTemplate object representing your custom template. Then use the SPListCollection.Add method to create a new list from this template. In code this would look something like this:

using (SPSite site = new SPSite("http://server/sites/site"))
using (SPWeb web = site.OpenWeb())
{
  SPListTemplateCollection templates = site.GetCustomListTemplates(web);
  SPListTemplate template = templates["MyTemplates"];
  Guid listId = web.Lists.Add("Title", "Description", template);
}

You have to use the internalname...something like this:

foreach (SPListTemplate template in web.ListTemplates)
 {
    if (template.InternalName.Equals("MyTemplateName")
     {
        return template;
     }
 }

Read my answer to this question . With that you should get a result from GetCustomListTemplates instead of just an empty list.

So, we gave up and instead have used a feature receiver to create the list totally from code. ListDefs are a complete PITA - C# is a much more logical way to create lists, plus you get the added benefit of being able to code upgrades to lists.

Thanks all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM