5

When we try to get list item properties, three ways of getting property I remember are,

ListItem["Property Name"]      //always work fine

ListItem.Properties["Property Name"] // works fine unless I upload a item with extension .msg and a-like

ListItem.Title .. and so on

Which one is the best way and why ?

5
  • ListItem["Property Name"] - Gets or sets a field value in the item based on the field’s title, internal name, or static name.

  • ListItem.Properties["Property Name"] - Gets metadata for the item.

In my practice the best usage is use ListItem[fieldId] for SharePoint OOTB fields, because you have SPBuiltInFieldIds enumeration.

  • ahh right, this approach works fine for custom fields too – Muhammad Raja Feb 20 '13 at 14:27
6

When you want to retrieve string values, use this type of strategy.

private string GetFieldValue(SPListItem li,string FieldName)
{
    var field = li.Fields.GetField(FieldName);
    object value = li[FieldName];
    return field.GetFieldValueAsText(value);
}

By doing a ListItem["FieldName"].Tostring(), you're running the risk of getting data back in a way that you dont expect. For Example, if your column is a Lookup Column, the data will come back as "0#Value". That's because Sharepoint saves the Option selected from the lookup list.

The method above is safe if you want to return strings only. When you want to Cast the type of the column/field , use this type of strategy:

SPFieldCurrency priceField = (SPFieldCurrency)item.Fields.GetFieldByInternalName("Retail_x0020_Price");

When we want to export lookup columns data using powershell script into CSV or Excel, ListItem.Properties[PropertyName] is best choice to use.

If we use ListItem[LookupPropertyName] for lookup columns, lookup column data will not be exported, instead we get blank fields

Read more on the subject here :

http://msdn.microsoft.com/en-us/library/ff521580(v=office.14).aspx

  • I have been looking for this article for sp 2007 but couldn't find. Thanks – Muhammad Raja Feb 20 '13 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.