Thursday, November 26, 2009

Add Lookup Column to SharePoint List Programmatically



In one of my previous article I discussed how to create a SharePoint list programmatically in C#. There I didn’t discuss how we can add lookup field for our newly created list. Let’s see how, 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();
        }
In the above code I have created Generic list and lookup 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".

8 comments:

  1. maybe I'm missing something obvious, but I don't see any sample code for adding the lookup column

    ReplyDelete
  2. @ Anonymous,
    please wait until the page fully loaded with syntaxhighlighter.
    if you cannot see the code, please refresh the page and see.
    thanks !

    ReplyDelete
  3. thanks a lot for share
    that's realy what i need(sorry for bad english)

    ReplyDelete
  4. Great post and blog, Saranga. You have an easy and very good approach. You would like to ask about we look up the User Information Info, eg: Department and Title. How we could query this kind of information? The lookup field is able to solve it?
    Thanks in advance!

    ReplyDelete
  5. Thanks for the example!

    I had one issue with your code. I think it has to do with the way you get the internal name of the "Title"-column. In my case, it was better to set the LookupField to "Title":

    $lkp.LookupField = "Title".

    ReplyDelete
  6. if textbox is empty then print 100% in current column with sharepoint list how resolve the problem

    ReplyDelete
  7. Is there any source to fix lookup field by JavaScript?

    ReplyDelete