Thursday, 24 April 2008

Retrieving values from SPField objects, not item.ToString()

When providing interaction with lists, whether it be via List Event Handlers or Web Parts, it helps to use the casting methods for the fields that you are going to be interacting with when both retrieving and setting values.

The most widely used scenario where this feature is best used is in Lookup, Choice, URL and User Fields, as the actual value that is stored by accessing the ListItem["name"].toString() is not always what may be expected.   Lookup Fields usually store values in this format, Id, #, ;, text.  which can amount to returning "1#;Title", when you were expecting "Title", and SPUser fields store a userid followed by the name, e.g. 16#:GavinMorgan

Below is a piece of code using some of the more widely used field types which casts the field value retrieved to its native type where more information can be accessed.

Something else to note here is that we consistently use the internal field.GetByInternalFieldName method to retrieve the field which ensures we always use the internal field name rather than than the title, as this is subject to change.

This example is from and ItemAdded event handler.

Code Snippet
  1. SPListItem item = properties.ListItem;
  2. //SPUser fields
  3. SPFieldUser userField = item.Fields.GetFieldByInternalName("UserInternalFieldName") as SPFieldUser;
  4. SPFieldUserValue userFieldValue = userField.GetFieldValue(item[userField.Title].ToString()) as SPFieldUserValue;
  5. SPUser user = userFieldValue.User;
  6. //Choice Fields
  7. SPFieldChoice choiceField = item.Fields.GetFieldByInternalName("ChoiceInternalFieldName") as SPFieldChoice;
  8. //To access the value
  9. string selectedChoice = choiceField.GetFieldValueAsText(item[choiceField.Title]);
  10. //To access list of choices in field
  11. foreach (string choice in choiceField.Choices)
  12. {
  13.     if (choice == "choice 1")
  14.     {
  15.         //do something with choices
  16.     }
  17. }
  18. //To add a new choice
  19. choiceField.Choices.Add("New Choice");
  20. choiceField.Update();
  21. //URL Fields
  22. SPFieldUrl urlField = item.Fields.GetFieldByInternalName("URLInternalFieldName") as SPFieldUrl;
  23. SPFieldUrlValue urlFieldValue = urlField.GetFieldValue(item[urlField.Title].ToString()) as SPFieldUrlValue;
  24. string url = urlFieldValue.Url;
  25. string desc = urlFieldValue.Description;

I will try to add more Field Types as i use them.

1 comments: