Get field value from Sharepoint list item

08/10/2013 14:00

      

Common functions for getting/setting  sharepoint list item field value

   

        public static void SetValueToListItem(SPItem item, string fieldStaticName, object value)
        {
            if (item != null)
            {
                if (TryGetFieldFromItem(item, fieldStaticName) != null)
                {
                    if (value != null)
                    {
                        item[fieldStaticName] = value;
                    }
                }
                else
                {
                   //todo, logg error
                }
            }

        }

 

public static object GetPropertyFromField(SPItem item, string fieldName)
        {
            object propertyValue = null;
            if (item != null && !string.IsNullOrEmpty(fieldName))
            {
                if (TryGetFieldFromItem(item, fieldName) != null && item[fieldName] != null)
                {
                    propertyValue = item[fieldName];
                }
            }
            return propertyValue;
        }


       public static string GetStringPropertyFromField(SPItem item, string fieldName)
        {
            string stringProperty = GetPropertyFromField(item, fieldName) != null ? GetPropertyFromField(item, fieldName).ToString() : string.Empty;
            return stringProperty;
        }


        public static SPField TryGetFieldFromItem(SPItem item, string fieldStaticName)
        {
            SPField existingField = null;
            if (item != null)
            {
                if (item.Fields.TryGetFieldByStaticName(fieldStaticName) != null)
                {
                    existingField = item.Fields.TryGetFieldByStaticName(fieldStaticName);
                }
            }
            return existingField;
        }


        public static void SetStringPropertyToField(SPItem item, string fieldName, string propertyValue)
        {
            SPField field = TryGetFieldFromItem(item, fieldName);
            if (field != null)
            {
                item[fieldName] = propertyValue;
                item.Update();
            }
        }