in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

akhileshtiwari

How to Create LookUp Column (SPFieldLookUp) and Associate it to a Field in List?

Code below is to create Lookup column at the SPWeb level and associate the lookup column to a Field in a  list.

--------------------------------------------------------------------------------------------------------------------------------------------------------------

using (SPSite site = new SPSite("http://<site_url>"))
            {
                using (SPWeb web = site.AllWebs["/"])
                {
                    SPList list = web.Lists["LookUpList"];                              //List to which LookUp Column will be associated.
                    string fieldName = "Look_Up_1";                                       //Name of the lookup field.
                    web.Fields.AddLookup(fieldName , list.ID, list.ParentWeb.ID, true);
                    web.Update();                                                                 //This step is very important.
                    SPFieldLookup field = web.Fields[fieldName] as SPFieldLookup;
                    field.ShowInDisplayForm = true;
                    field.LookupField = list.Fields["ID"].Title;                           //Field to which the LookUp column will be associated.

                  //Lookup Column can be assigned values from this field only.
                    field.Update();

               }

          }
 

--------------------------------------------------------------------------------------------------------------------------------------------------------------
 

As usual refer to the inline comments for the explanation of the the code.

 Akhilesh Tiwari

Comments

No Comments

Leave a Comment

(required )  
(optional )
(required )  
Add

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts