How to get all possible values ​​for SPFieldLookup

I have a search field in sharepoint that just links to another list. I wonder how I programmatically list all the possible values ​​for this field? For example, my search field "Actual city" refers to the list of "Cities" and the column "Title", I have 3 cities. In the code, I would like to get a list of all possible values ​​for the "Actual city" field, 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

+3
source share
4 answers

I wrote some code to handle this for my project just the other day. Perhaps this 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;
        }
+4
source

, , , . SPFieldLookup , : LookupField LookupList

, , , . , . f.GetAllPossibleValues();.

0

, ?

, , Actual City null, :

<Where><IsNotNull><FieldRef Name='Actual City'/></IsNotNull></Where>

List<SPFieldLookupValue> result = new List<SPFieldLookupValue>(returnedItemCount * 5);

foreach (SPListItem item in queriedItems) {
  object lookup = item["Actual City"];
  SPFieldLookupValueCollection lookupValues = new SPFIeldLookupValueCollection(
    (lookup != null) ? lookup.ToString() : ""
  );
  foreach (SPFieldLookupValue lookupValue in lookupValues) {
    if (!result.Contains(lookupValue)) {
      result.Add(lookupValue);
    }
  }
}

HashTable, LookupId , LookupValue int id, , HashTable.ContainsKey(lookupId)... -, , , , , ...

0

, , Title . , SharePoint , GetAllPossibleValues ​​(), , , , CAML, .

0
source

Source: https://habr.com/ru/post/1739265/


All Articles