Pages

Subscribe:

Wednesday, December 14, 2011

Create SharePoint list programmatically C#

In this article I am going to show how to create a SharePoint List and fields Programmatically using c#
public void CreateList()
{
    //choose your site
    SPSite site = new SPSite("http://sps2010");
    SPWeb web = site.OpenWeb();
    SPListCollection lists = web.Lists;

    //create new Generic list called "Custom List"
    lists.Add("Custom List ", "list Description",SPListTemplateType.GenericList);
    SPList newList = web.Lists["Custom List "];

    //create Text type new column called "Name"
    newList.Fields.Add("Name", SPFieldType.Text, true);

/*create lookup type new column called "Lookup Column"
    Here I am going to get the information from the "Title"
    column of a list called "LookUp List"
   * /
    SPList lookupList = web.Lists["LookUp List"];
    newList.Fields.AddLookup("Lookup Column", lookupList.ID, false);
    SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Lookup Column"];
    lkp.LookupField = targetList.Fields["Title"].InternalName;
    lkp.Update();

    //make new column visible in default view
    SPView view = list.DefaultView;
    view.ViewFields.Add("Name");
    view.ViewFields.Add("Lookup Column ");
    view.Update();
}

1 comments:

  1. I know you posted this article awhile ago but it was quite helpful. :)

    Thank you.

    ReplyDelete