Friday, November 13, 2009

Create SharePoint list programmatically C#



In this article I’m going to discuss how we can create a SharePoint list programmatically in c# and how we can add columns to the created list. Actually this is very simple task; 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 list = web.Lists["My List"];

            // create Text type new column called "My Column" 
            list.Fields.Add("My Column", SPFieldType.Text, true);

            // make new column visible in default view
            SPView view = list.DefaultView;
            view.ViewFields.Add("My Column");
            view.Update();
        }
In the above code I have created Generic list and normal Text column. You can use whatever list type and field type according to your requirement. To learn more about SharePoint lists, follow "SharePoint List C# Part 1".

If you want to add lookup columns please refer "Add Lookup Column to SharePoint List programmatically".

To learn how to create List View, refer "Create SharePoint List View Programmatically".

3 comments:

  1. Hi rahul,
    First, thanks for the comment.
    You have a useful resource collection.
    thanks for sharing !

    ReplyDelete
  2. i want to ask where to write this code !! or could u tell which projcet to make and in which file to put this code thanks !!

    ReplyDelete
  3. @ Imran,

    If you have remote access to the SharePoint server you can create console application and run the above code in the SharePoint server machine. If you haven't access to the SharePoint server computer then you have to use Web Services to get the work done.

    Thanks !

    ReplyDelete