Search This Blog

Wednesday, January 30, 2013

SPFieldLookupValue class

Remarks





Instances of this class represent a single field value for a lookup field. Lookup fields can have multiple values or just one. You can determine which is the case by checking the value of the lookup field's AllowMultipleValues property. If the property returns true, the field can have multiple values; if it returns false, it cannot.
If a lookup field does not allow multiple values, the field value is an object of type String that contains the ID of the item in the list that the lookup field points to plus the value of the field in the item that the lookup field points to. You can pass this string as an argument to the SPFieldLookupValue(String) constructor to create an SPFieldLookupValue object. Then you can get the list item ID from the LookupId property and the value of the field in the list item from the LookupValue property.
If a lookup field allows multiple values, then the field value is an object of type SPFieldLookupValueCollection that is boxed as type Object. The SPFieldLookupValueCollection object is a collection of SPFieldLookupValue objects. You can extract the field values by enumerating the collection and accessing each object's LookupValue property.


The following example demonstrates how to set the value of a lookup field.
The example code is a console application that gets references to two related lists, Customers and Orders. Each item in the Customers list represents a customer record, and the ID field in the item is used to identify a customer. Each item in the Orders list represents an order placed by a customer. The Orders list has a lookup field named Customer ID that points to the ID field in the Customers list, identifying the customer who placed the order.
Code in a foreach loop iterates through the list of customers, adding a new item to the Orders list for each customer on the Customers list. In each case, the code sets the value of the lookup field, Customer ID, to link the order to the customer.


using System;
using Microsoft.SharePoint;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://localhost"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList customerList = web.Lists.TryGetList("Contoso Customers");
                    SPList orderList = web.Lists.TryGetList("Contoso Orders");

                    if (customerList != null && orderList != null)
                    {
                        SPListItemCollection customers = customerList.Items;
                        SPListItemCollection orders = orderList.Items;

                        string fieldName = "CustIDLookup";
                        if (!orderList.Fields.ContainsField(fieldName))
                            return;
                        
                        SPField lookupFld = orderList.Fields.GetField(fieldName);

                        foreach (SPListItem customer in customers)
                        {
                            SPListItem order = orders.Add();
                            order[SPBuiltInFieldId.Title] = "Thank you!";
                            order.Update();

                            SPFieldLookupValue value = new SPFieldLookupValue(customer.ID, customer.ID.ToString());
                            order[lookupFld.Id] = value.ToString();
                            order.Update();
                        }
                    }
                }
            }
        }
    }
}


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.



Setting the value of LookUp Fields in C#


LookUp Fields are a common sight in SharePoint environments, but working with them is not as straightforward as one might expect. Setting a LookUp Field Value (object type SPFieldLookupValue) on a list item offers several options:

 

1. Setting the value to a SPFieldLookupValue

This one is obvious. The SPFieldLookup value property is – as with all field values – of type object in the SharePoint object model, but is internally used as a SPFieldLookupValue.

2. Setting the value to a formatted String

LookUp Field Values have a string representation of “(ID);#(VALUE)”, i.e. “2;#Second Entry”. Setting the value to a String in the before mentioned format works as well as it is converted to a SPFieldLookupValue.

3. Setting the value to an ID only (which is an Integer)

To my surprise, the value can be set to the ID only without raising any errors.

4. Not working: Setting the value to the String value only

Unfortunately, just setting the value to the desired value and skipping the ID part does not work and will throw an “Index Out Of Range” Exception. But the GUID of the LookUp List is conveniently stored in the SPFieldLookup object. In some situations it is useful to set the value using Strings and I wonder why that is not a build-in option. The following code achieves this goal:

 
public static SPFieldLookupValue getLookUpValue(string lookupValue, SPList myList, String fieldname)
        {
            SPFieldLookup lookUpField = (SPFieldLookup)myList.Fields[fieldname];
            SPList lookupSourceList = myList.ParentWeb.Lists[lookUpField.LookupList];

            SPQuery query = new Microsoft.SharePoint.SPQuery();
            query.Query = String.Format("{0}", lookupValue);
            SPListItemCollection listItems = lookupSourceList.GetItems(query);

            return new SPFieldLookupValue(listItems[0].ID.ToString());
        }

        // use like this:
        item["myLookUpField"] = getLookUpValue("the new value", item.ParentList, "myLookUpField");

 

 

Properly Populating and Retrieving SharePoint Field Data 

 

http://sharepointcodeblock.blogspot.in/2008/07/properly-populating-and-retrieving.html

 

 SharePoint uses a lot of field types that have different underlying schemas, delimiters and formats. I see a lot of people reverse engineer the field information and "hack" the data into the list using a string such as "1;#Title" for a lookup field. Well this isn't exactly best practice so I've put together a reference table below to assist in using the correct data types for populating or retrieving information from a SharePoint list.

Lookup Field

Field Class: SPFieldLookup Field Value Class: SPFieldLookupValue Populating Information: item["FieldName"] = new SPFieldLookupValue("Title"); // SharePoint will do the lookup as long as the LookupValue's are uniqueitem.Update();oritem["FieldName"] = new SPFieldLookupValue(1, "Title");item.Update(); Retrieving Information: SPFieldLookupValue itemValue = item["FieldName"] as SPFieldLookupValue;int id = itemValue.LookupId;string value = itemValue.LookupValue;

Multiple Lookup Field

Field Class: SPFieldLookup Field Value Class: SPFieldLookupValueCollection Populating Information: SPFieldLookupValueCollection itemValues = SPFieldLookupValueCollection();itemValues.Add(new SPFieldLookupValue(1, "Title"));item["FieldName"] = itemValues;item.Update(); Retrieving Information: SPFieldLookupValueCollection itemValues = item["FieldName"] as SPFieldLookupValueCollection;foreach (SPFieldLookupValue itemValue in itemValues){int id = itemValue.LookupId;string value = itemValue.LookupValue;}

User Field

Field Class: SPFieldUser Field Value Class: SPFieldUserValue Populating Information: web.EnsureUser(@"domain\username");SPUser user = web.AllUsers[@"domain\username"];item["FieldName"] = user;item.Update(); Retrieving Information: string currentValue = item["FieldName"].ToString();SPFieldUser userField = list.Fields.GetFieldByInternalName("FieldName");SPFieldUserValue itemValue = (SPFieldUserValue)userField.GetFieldValue(currentValue);SPUser user = itemValue.User;

URL Field

Field Class: SPFieldUrl Field Value Class: SPFieldUrlValue Populating Information: SPFieldUrlValue urlValue = new SPFieldUrlValue();urlValue.Url = "http://www.google.com";urlValue.Description = "Google";item["FieldName"] = urlValue;item.Update(); Retrieving Information: SPFieldUrlValue urlValue = new SPFieldUrlValue(item["FieldName"].ToString());string url = urlValue.Url;string description = urlValue.Description;

Multiple Choice Field

Field Class: SPFieldMultiChoice Field Value Class: SPFieldMultiChoiceValue Populating Information: SPFieldMultiChoiceValue itemValue = new SPFieldMultiChoiceValue();itemValue.Add("Choice 1");itemValue.Add("Choice 2");itemValue.Add("Choice 3");item["FieldName"] = itemValue;item.Update(); Retrieving Information: SPFieldMultiChoiceValue itemValue = new SPFieldMultiChoiceValue(item["FieldName"].ToString());foreach (string choice in itemValue){// value is in choice}

 

For "multiple lookup Fields", the below code is used:
SPFieldLookupValueCollection itemValues = SPFieldLookupValueCollection(); 
itemValues.Add(new SPFieldLookupValue(1, "Title")); 
item["FieldName"] = itemValues; 
item.Update(); 

 

 

 

using (SPSite site = new SPSite("http://servername"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["My Skills"]; //List which has lookupfield TechSkills
SPListItemCollection itemCollection;
itemCollection = list.Items;
foreach (SPListItem item in itemCollection)
{
SPFieldLookupValue lookupField = new SPFieldLookupValue(item["TechSkills"].ToString());
string lookUpValue = lookupField.LookupValue;
Console.WriteLine("List item actual value:" + item["TechSkills"].ToString());
Console.WriteLine("List item lookfield value:" + lookUpValue);
}
SPListItem listItem = itemCollection[0];
listItem["Skill Name"] = new SPFieldLookupValue(1, "ASP.Net"); //ID field of ASP.Net is 1
listItem.Update();
}
}

No comments:

Post a Comment