0
votes

I'm having trouble accessing the value of a calculated field from a list which is in a lookup field on another list in codebehind for SharePoint.

A ListFieldIterator on a page displays a load of options to a user. I need to perform some back-end validation on some particular selections the user has made.

I have a list called "Event Type" from which a user can select Play, performance, display etc. This list has 4 columns - description, enabled, default and filtered. Filtered is a calculated column which is generated based upon the options chosen on the other columns.

The list Events has a column which is a lookup to this list, and which displays the filtered column.

Now on the page this all works great. The options are displayed to the user and they can make their selection. Before adding the calculated field I could access the choice made by doing the below

SPFieldLookup eventTypeField = ListFieldIterator.Item.Fields.GetField("Event_x0020_Type") as SPFieldLookup;
if (eventTypeField.GetFieldValueAsText(ListFieldIterator.Item["Event_x0020_Type"]) == "Performance")
{
    // some other logic
    errorMessages.Add("There is an error here");                
}

Now however when accessing the field in this way I just get an empty string back.

If I attempt to access the chosen item with

string value = eventFields.Item["Event_x0020_Type_x0020_1"].ToString();

Then I get back "8" which is the position in the list of the item I chose. (it changes based on what item in the list I select)

This post Get value of calculate field seems related but I can't see an obvious way to get a calculated field from the lookupfield.

Any suggestions appreciated

1

1 Answers

1
votes

It turns out that when using either a lookup column or a lookup column with a calculated field in, as I was, I was going about things the wrong way. This post put me onto the solution. The code is also below.

Essentially I need to access the value stored in the control of the ListFieldIterator and not the value from the item. The code below (from the link above) provides a nice way to do this.

public static List<T> GetControlsOfType<T>(this ControlCollection controls)
{
  List<T> resultList = new List<T>();
  foreach (Control control in controls)
  {
    if (control is T)
      resultList.Add((T)((object)control));
    if (control.Controls.Count > 0)
    {
      resultList.AddRange(GetControlsOfType<T>(control.Controls));
    }
  }
  return resultList;
}


public object GetFieldValue(ListFieldIterator lfi, string fieldName)
{
  FormField formField = lfi.Controls.GetControlsOfType<FormField>().Where(f => f.FieldName == fieldName).FirstOrDefault();
  if (formField == null) return null;
  return formField.Value;
}