Tuesday, 20 January 2015

Adding Lists Programmatically in SharePoint

Developers often look for creating Custom Lists in SharePoint sites Programmatically.
Here is a sample code for creation of SharePoint Lists Programmatically
public void createSPList(string strListName)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
    //Open your site
    SPSite site = new SPSite(Constants.strSiteURL);
    SPWeb web = site.OpenWeb();
    web.AllowUnsafeUpdates = true;
    SPListCollection lists = web.Lists;
    // create new Generic list
    lists.Add(strListName, "My Description", SPListTemplateType.GenericList);
    //Add Columns to SP List
    SPList newSPList = web.Lists[strListName];
    // create new column "User Name" and Field Type “Text”
    newSPList.Fields.Add("User Name", SPFieldType.Text, true);
    //creating lookup type column to this New List
    //Here I am getting information from the "Title" column from “Employee Roles” List
    SPList List2 = web.Lists["Employee Roles"];
    newSPList.Fields.AddLookup("Lookup Column", List2.ID, false);
    SPFieldLookup spLookup = (SPFieldLookup) newSPList.Fields["Lookup Column"];
    spLookup.LookupField = List2.Fields["Title"].InternalName;
    spLookup.Update();
    // Adding newly added column to default view
    SPView view = newSPList.DefaultView;
    view.ViewFields.Add("User Name");
    view.ViewFields.Add("Lookup Column");
    view.Update();
    newSPList.Update();
    web.AllowUnsafeUpdates = false;
    site.Dispose();
});
}



SharePoint List generation depends on the List Template type that we are specifying during list creation. one can create lists of type Custom Lists(Generic Lists), Document Library, Announcements, Picture Library, Tasks, Survey, Discussion Board, Contacts, Links, etc.

You can specify list template type in the below code highlighted

 lists.Add(strListName, "My Description", SPListTemplateType.GenericList);

No comments:

Post a Comment