Getting a SharePoint Field Value In C#

Someone asked me this morning when doing a code review of my code how I got a field value. They were not looking very closely. Here is how I do it, although there are 50,000 other ways of doing it.

This is my getFieldValue helper method, that will be called at other instance points throughout the code.

  1. public static string getFieldValue(SPListItem listItem, string fieldName)
  2. {
  3. string text = string.Empty;
  4. if (fieldName == string.Empty)
  5. {
  6. return text;
  7. }
  8. try
  9. {
  10. object myObj = listItem[fieldName];
  11. return ((myObj != null) ? myObj.ToString() : string.Empty);
  12. }
  13. catch
  14. {
  15. return string.Empty;
  16. }
  17. }

Once the helper method is defined, then it can be consumed in something like a foreach loop to return SharePoint list items based on conditions. If the condition is not met, it will return null.

  1. private SPListItem getItemText(SPListItemCollection spItems, string text)
  2. {
  3. foreach (SPListItem item in spItems)
  4. {
  5. if (getFieldValue(item, this.myList.myColumn) == text)
  6. {
  7. return item;
  8. }
  9. }
  10. return null;
  11. }
share save 171 16 Getting a SharePoint Field Value In C#

3 Comments

  1. John says:

    Very nice method and a good coding practice. Nice work.

  2. Jeff says:

    Does not always work. If i create a column “project”, then delete it, then create a column “project” again, it’s field name is actually now “project0″ despite visibly showing project.

  3. Jeff says:

    skip all that – it’s still funky. the reason is that display name and internal name arent always the same…and this only works when they are the same. Something like this might be a bit more stable if columns ever change (i’ve crunched the code for brevity):

    SPListItemCollection qItems = splc["ListName"].GetItems(query);

    foreach (SPListItem spli in qItems)
    {
    fieldValue = spli[spli.Fields.GetField("ColName").InternalName];
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>