SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ?

share|improve this question
up vote 5 down vote accepted
  • 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.

share|improve this answer
    
ahh right, this approach works fine for custom fields too – Muhammad Raja Feb 20 '13 at 14:27

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

share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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