Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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();
spQuery.Query=@"<Where>
            <Eq>
                <FieldRef Name='Active' />
                <Value Type='Boolean'>1</Value>
            </Eq>
        </Where>";
SPListItemCollection collListItems = spList.GetItems(spQuery);
foreach (SPListItem listItem in collListItems)
{
    string newsCaption = listItem["NewsCaption"].ToString();
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

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

share|improve this answer
    
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
    
this answer is very usefull for me Thanks A lot –  user6327 Jan 9 '12 at 15:26
add comment

Instead of using:

listItem["NewsCaption"].ToString()

Use:

Convert.ToString(listItem["NewsCaption"])
share|improve this answer
add comment

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.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spquery.viewfields.aspx

share|improve this answer
add comment

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.