Wednesday, July 28, 2010

Create a SharePoint list Dynamically using list template

Somebody sent me question asking how to create a sharepoint list using list template ?
Here is the sample code I have written, its working, if you have any doubt you can send me an email @ s_tiwari05@yahoo.com

Before running this code you have to have a list template created and stored into list template gallery, I am reading it from there and creating one instance of that and using it to create actual link. If you have many sites in he site collection where you want to create list you can put this code into loop and create list in each site.

web1.AllowUnsafeUpdates = true;
//Create Risk-Issue-Chnage List
txtStatus.Text = "";
lblwsname.Text = web1.Url;
SPListTemplate splt;
//Create site
SPSite site=new SPSite();
//Create web
SPWeb web=site.OpenWeb();
SPListTemplateCollection spltc;
try
{
//Retrieve all the list templates from template gallery
spltc = site.GetCustomListTemplates(web);
//Retrieve specific template you are looking for.
splt = spltc["MyListName"];

splColl = web1.Lists;
gd = splColl.Add("MyListName", "MyListTitle", splt);
splColl[gd].Update();


}
catch (Exception ex)
{
SW = File.AppendText("C:\\DeploymentLog.txt");
SW.WriteLine(" Error Occurred while creating list : " + web1.Url + " : " + ex.Message + " " + DateTime.Now.ToString() + " " + ex.StackTrace);
SW.WriteLine("--------------------------------------------------");
SW.Close();
txtStatus.Text = txtStatus.Text + Environment.NewLine + " Error Occurred while creating list, see log for detail......";
}


Sanjay Tiwari
Yashi Technologies LLC
Dallas, Texas