0

I was create Console Project and getListItems in C#, in List items there are empty values, how to skip them so that an error does not appear and by the way this did not happen before, appeared only when switching to another Visual studio 2017.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Microsoft.SharePoint.SPItem.this[string].get returned null.

using Microsoft.SharePoint;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConApp
{
    public class Item
    {
        public string title { get; set; }
        public string room { get; set; }
    }

    //Class declaration array
    public class RootObject
    {
        public RootObject()
        {
            items = new List<Item>();
        }
        public List<Item> items { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<string> array = new List<string>();

            using (SPSite SPsite = new SPSite("http://sp-test/sites/test"))
            {
                using (SPWeb SPWeb = SPsite.OpenWeb())
                {
                    SPList list = SPWeb.Lists["Contact"];

                    SPListItemCollection oitems = list.GetItems(new SPQuery()
                    {
                        Query = @""
                    });
                    RootObject objs = new RootObject();
                    foreach (SPListItem item in oitems)
                    {
                        objs.items.Add(new Item
                        {
                            fio = item["Title"].ToString(),
                            room = item["Room"].ToString(),
                        });
                    }
                    var rootarray = objs.items;
                    for (int i = 0; i < array.Count; i++)
                    {
                        var test = rootarray[i];
                        var test1 = test.room;
                    }
                }
            }
        }
    }
}
0

You have two potential lines where this error can happen, so you need to change that code to perform null-check.

fio = item["Title"].ToString(),
room = item["Room"].ToString(),

you can change that part to:

fio = (item["Title"] != null) ? item["Title"].ToString() : "", //you can also use null instead of ""
room = (item["Room"] != null) ? item["Room"].ToString() : ""

As for your question on why this didn't happen before, that's because in your previous executions all the items had the values in both Title and Room fields.

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.