Create SharePoint List Programmatically

Create a SharePoint list programmatically in C#.

Add lookup field for our newly created list.

This is a sample code.

public void createList()
{
   
// choose your site
   
SPSite site = new SPSite("http://merdev-moss:5050");
   
SPWeb web = site.OpenWeb();
   
SPListCollection lists = web.Lists;

    // create new Generic list called "My List"

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

 

    SPList newList = web.Lists["My List"];

    // create Text type new column called "My Column"
   
newList.Fields.Add("My Column", 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 "User Roles"
   
*/

   
SPList targetList = web.Lists["User Roles"];

    newList.Fields.AddLookup("Lookup Column", targetList.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 = newList.DefaultView;
   
view.ViewFields.Add("My Column");
   
view.ViewFields.Add("Lookup Column");
   
view.Update();

}

Ebook Download
View all
Learn
View all