Tuesday, June 18, 2013

Lookup: Adding data into SharePoint Lookup column Programatically

Adding data into SharePoint Lookup column Programatically:


Logic:
For Updating Lookup field Item, it takes ID only.
Not a string type value:

Here CountryLookup is lookup field in UploadExcelData List:
Pic:1


It is Taking the values from Country List with field is Country.
Pic:2

Pic:3
Pic:4

=====================================================
 SPList lstExamStatus = web.Lists.TryGetList("Country");
            SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item["Country"].ToString() == itemname)
                {
                    id = item.ID;
                    break;
                }
            }

 if (ID != 0)
  {
         addNewItem["CountryLookup"] = ID;
   }
----------------------------------------------------------------------------------------------------------------------
Note: itemname (India, England France). If you want to update India. itemname= "India";
===========================================================


========================================================
===========================@============================

Another Case:

Source List: ExamStatus: Title having columns (Pass, Fail...)
Destination: SureStep: Status Lookup field (from Exam Status).

  string lstExamStatus = "ExamStatus";
            string examStatusField_Title = "Title";                                   
            SPListItemCollection lstItemColl = web.Lists["SureStep"].Items;
            SPListItem item = lstItemColl.Add();
            item["Title"] = "FirstName-Ravikumar1"; // Optional not neccesary

        // get_ID() method to retrive perticular Id.

            int ID = get_ID(web, lstExamStatus, examStatusField_Title, "Pass"); //Pass (Item Name) Selected value from drop down
            if (ID != 0)
                item["Status"] = ID;
            item.Update();



        public static int get_ID(SPWeb web, string list, string field, string itemname)
        {
            int id = 0;
           SPList lstExamStatus = web.Lists.TryGetList("ExamStatus");
           SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item.DisplayName == itemname)
                {
                    id = item.ID;
                    break;
                }
            }
            return (id);

No comments:

Post a Comment