Wednesday 16 January 2013

Create sharepoint list programmatically

I have written a sample code showing how to create custom sharepoint list programmatically .

-------------------------------------
            SPSite site = new SPSite("URL");
            SPWeb web = site.OpenWeb();
            SPListCollection lists = web.Lists;
            lists.Add("Programmatically List", "Here the list is being created programmatically", SPListTemplateType.GenericList);
            SPList newList = web.Lists["Programmatically List"];
            newList.Fields.Add("My Column", SPFieldType.Text, true);
            newList.Fields.Add("DOB", SPFieldType.DateTime, true);
           
           // Lookup from another list and adding that column along with the fileds present
            SPList targetList = web.Lists["InfoValidation"];
            newList.Fields.AddLookup("Message", targetList.ID, false);
            SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Message"];
            lkp.LookupField = targetList.Fields["Message"].InternalName;
            lkp.Update();

            SPView view = newList.DefaultView;
            view.ViewFields.Add("My Column");
            view.ViewFields.Add("DOB");
            view.ViewFields.Add("Message");
            view.Update();
            Console.WriteLine("List Created Successfully");
            Console.Read();
            site.Dispose();
            web.Dispose();

Run this as a console application.

No comments:

Post a Comment