How to get all possible values for SPFieldLookup

Anton Polyakov picture Anton Polyakov · Mar 31, 2010 · Viewed 9.8k times · Source

I have a lookup field in sharepoint which just references another list. I wonder how do I programatically enumerate all possible values for this field? For example, my lookup field "Actual City" refers list "Cities" and column "Title", I have 3 cities there. In code I would like to get list of all possible values for field "Actual City", smth like (metacode, sorry):

SPFieldLookup f = myList["Actual City"];
Collection availableValues = f.GetAllPossibleValues();
//this should return collection with all cities a user might select for the field

Answer

Eric picture Eric · Jun 24, 2013

I wrote some code to handle this for my project just the other day. Perhaps it will help.

    public static List<SPFieldLookupValue> GetLookupFieldValues(SPList list, string fieldName)
    {
        var results = new List<SPFieldLookupValue>();
        var field = list.Fields.GetField(fieldName);

        if (field.Type != SPFieldType.Lookup) throw new SPException(String.Format("The field {0} is not a lookup field.", fieldName));

        var lookupField = field as SPFieldLookup;
        var lookupList = list.ParentWeb.Lists[Guid.Parse(lookupField.LookupList)];
        var query = new SPQuery();

        query.Query = String.Format("<OrderBy><FieldRef Name='{0}'/></OrderBy>", lookupField.LookupField);

        foreach (SPListItem item in lookupList.GetItems(query))
        {
            results.Add(new SPFieldLookupValue(item.ID, item[lookupField.LookupField].ToString()));
        }

        return results;
    }

Then to use it, your code would look something like this:

        var list = SPContext.Current.Web.Lists["My List"];
        var results = GetLookupFieldValues(list, "Actual City");

        foreach (SPFieldLookupValue result in results)
        {
            var value = result.LookupValue;
            var id = result.LookupId;
        }