The NewsCaption field exists (both display and internal name is NewsCaption). I even saw it exists when I went to watch window and show this field listed in the SchemaXML for the fields element. I am kinda lost.

SPList spList = web.Lists["My Picture Library"];
SPQuery spQuery = new SPQuery();
                <FieldRef Name='Active' />
                <Value Type='Boolean'>1</Value>
SPListItemCollection collListItems = spList.GetItems(spQuery);
foreach (SPListItem listItem in collListItems)
    string newsCaption = listItem["NewsCaption"].ToString();

Is there data in the field that you are calling .ToString on? It sounds like maybe the field is null.

  • I dont understand, after populating the field with value then I dont get the error. How can I handle null values? – David Mike Jul 1 '11 at 17:26
  • Something like: object newsCaptionField = listItem["NewsCaption"]; if (newsCaptionField != null) { string newsCaption = newsCaptionField.ToString(); } – Efil4zaggin Jul 1 '11 at 17:35
  • You're getting the error because you are trying to call .ToString() on a null object. As Efil says, you could do SPField newsCaption = listItem["NewsCaption"];. That won't error out, and if the object doesn't exist, it will be null. – Tim Gabrhel Jul 1 '11 at 18:17
  • Thank you Tim and Efil. You guys are true SP savers. Thanks – David Mike Jul 1 '11 at 20:10

Instead of using:




I can't see your whole snippet related tot he spList.GetItems(...) call. Do you have a view name specified? I notice you have not specified the SPQuery.ViewFields property value to define what fields you want returned by your query. It is a good practice to always specific the fields you want returned from a query.

The field is either null, or the field is not being returned in the default fields list for the query.


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.