Sunday, March 15, 2015

Adding new item with lookup column value

Adding the new city name in the "Cities" list where country name column has been used as "Look up" column.

Lookup column enables the user to retrieve the data from the other list within the site.

User need to add the city name in the text box and select the country name
from the drop down list box (lookup column).
To enact this scenario through programmatically,we can use SPFieldLookupValue class in SharePoint.

SPFieldLookupValue takes the Countries list's Item ID where UAE been added.

 using(SPSite site = SPContext.Current.Site)
            {
                using(SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;
                        var list = web.Lists["Cities"].AddItem();
                        var item = list.ListItems.Add();
                        SPFieldLookupValue lookupVal = new SPFieldLookupValue(3, "UAE");
                        item["Title"] = "Abu Dhabi";
                        item["Country"] = lookupVal;
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                        updateStatus.Text = "Item updated successfully !";
                    }
                    catch(SPException ex)
                    {
                        updateStatus.Text = ex.Message;
                    }
                }