Friday, August 5, 2011

How to programmatically manipulate with Lookup field

Lookup field allows us to create relation between two lists, but this is not what I want to write about. Here is some source where you can find how to create Lookup field.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=574
More information about Lookup field you would find if you would search on the Internet.
But for now let's focus at programmatical part of lookup field.

Data in lookup field are represented as String. This String looks like this: ID;#FieldValue
You could write your own class to work with this field but why to code something if there is everything done already :)
We'll need to use SPFieldLookup, SPFieldLookupValue and SPFieldLookupValueCollection classes.
SPFieldLookup- represents a lookup field
SPFieldLookupValue - contains the value for an SPFieldLookup object
SPFieldLookupValueCollection - contains the values for an SPFieldLookup object that can contain multiple values

Ok then, it should be enough for the start and lets focus at implementation of this classes. As always you can choose some different ways how you will treat your lookup field.

  • If you know that the field is definitely type of Lookup and there is no Multiple selection checked and field is filled(is required field box checked), you can use this simple short code:
            //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                   //Loop through all items in the list
                    foreach (SPListItem row in list.Items)
                    {
                        SPFieldLookupValue myLookup = new SPFieldLookupValue(row["MyLookUpColumn"].ToString());
                        Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                    }
                }
            }


  • In a case you use multiple selection, you would probably want to get all items in your lookup field. For that purpose you can use SPFieldLookupValueCollection class which will enable you to go through all items in your lookup field. Here is the code:


            //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                    //Loop through all items in the list
                    foreach (SPListItem row in list.Items)
                    {
                        //Creates new SPFieldLookupValueCollection instance from our look up field
                        SPFieldLookupValueCollection myLookupCollection = new SPFieldLookupValueCollection(row["MyLookUpColumn"].ToString());
                        //Loop through all items in collection
                        foreach (SPFieldLookupValue myLookup in myLookupCollection)
                        {
                            Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                        }
                    }
                }
            }



  • What should you do if you don't know if your field is type of Lookup? Even here is simple solution because you can go through all fields in your list and check for particular dataType. Actually this doesn't involve just Lookup field because you can use it whenever you need to find out what data types are in your list. It is simple like this:


          //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                    //Title of our lookup column
                    string myLookupColumnName = string.Empty;
                    //Name of field to check if it is type of lookup
                    string fieldToCheckForLookup = "TestLookup";
                    //Loop through all fields in list
                    foreach (SPField field in list.Fields)
                    {
                        //Find Lookup field type
                        if (field is SPFieldLookup)
                            if (field.Title == fieldToCheckForLookup)
                            {
                                //do something clever with our lookup field
                                Console.WriteLine("Our field is type of lookup.");
                                myLookupColumnName = field.Title;
                            }
                    }


                    if (myLookupColumnName != string.Empty)
                        foreach (SPListItem row in list.Items)
                        {
                            //Tries to get data from field
                            try
                            {
                                //Creates new SPFieldLookupValueCollection instance from our look up field
                                SPFieldLookupValueCollection myLookupCollection = new SPFieldLookupValueCollection(row[myLookupColumnName].ToString());
                                //Loop through all items in collection
                                foreach (SPFieldLookupValue myLookup in myLookupCollection)
                                {
                                    Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                                }
                            }
                            catch(Exception ex)
                            {
                                Console.WriteLine("An error occured: " + ex.Message);
                            }
                        }
                    else
                        Console.WriteLine("{0} field was not type of lookup.", fieldToCheckForLookup);
                }
            }


I think there is more ways how to work with lookup field but this definitely works for me :)
Ok, that should be all. If you would find it interesting or helpful I would be glad, but if there is something you don't agree with please comment it or let me know ;)
David

No comments:

Post a Comment