Friday, 6 July 2012

Create list and list column programatically


            SPSite mySite = (SPSite)properties.Feature.Parent;
            SPWeb myWeb = mySite.OpenWeb();
            myWeb.AllowUnsafeUpdates = true;

           
            myWeb.Lists.Add("NewsAndEvents", "The information about News and Archieves", SPListTemplateType.GenericList);
            SPList myList = myWeb.Lists["NewsAndEvents"];
            SPView defaultView = myList.DefaultView;

            SPFieldDateTime eventDate = (SPFieldDateTime)myList.Fields[myList.Fields.Add("EventDate", SPFieldType.DateTime, true)];
            eventDate.Description = "The Date of the Event";
            eventDate.Update();
            defaultView.ViewFields.Add(eventDate);

            SPFieldMultiLineText eventDescription = (SPFieldMultiLineText)myList.Fields[myList.Fields.Add("EventDescription", SPFieldType.Note, true)];
            eventDescription.Description = "Description about the event";
            eventDescription.RichText = true;
            eventDescription.RichTextMode = SPRichTextMode.FullHtml;
            eventDescription.Update();
            defaultView.ViewFields.Add(eventDescription);

            SPFieldUrl pictureURL = (SPFieldUrl)myList.Fields[myList.Fields.Add("Picture", SPFieldType.URL, false)];
            pictureURL.Description = "The URL address of the picture";
            pictureURL.Update();
            myList.Update();
            defaultView.ViewFields.Add(pictureURL);
            defaultView.Update();
            myList.Update();
            myWeb.AllowUnsafeUpdates = false;