object refrence not set to an instance of an object error of splistitemcollection.getdatatable RRS feed

  • Question

  • HI

    I have the error message object refrence not set to an instance of an object in splistitemcollection.getdatatable(). i used

     SPFieldCollection fieldColl = collListItems.Fields;
    int dummyVar = collListItems.Fields.Count;

    before DataTable dt = collListItems.GetDataTable(); but i still have this problem. can you help please?

    thank you

    Monday, January 9, 2017 8:12 AM

All replies

  • Hi minayi,

    Please check if the SPListItemCollection object is valid and make sure it is not null.

    Also, here is a code demo about using SPListItemCollection to get multiple list items:

    using (SPSite site = new SPSite("http://localhost"))
                using (SPWeb web = site.OpenWeb())
                   // Build a query.
                   SPQuery query = new SPQuery();
                   query.Query = string.Concat(
                                     "<FieldRef Name='Status'/>",
                                     "<Value Type='CHOICE'>Not Started</Value>",
                                     "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                     "<FieldRef Name=’Priority’ Ascending='TRUE' />", 
                   query.ViewFields = string.Concat(
                                       "<FieldRef Name='AssignedTo' />",
                                       "<FieldRef Name='LinkTitle' />",
                                       "<FieldRef Name='DueDate' />",
                                       "<FieldRef Name='Priority' />");
                   query.ViewFieldsOnly = true; // Fetch only the data that we need.
                   // Get data from a list.
                   string listUrl = web.ServerRelativeUrl + "/lists/tasks";
                   SPList list = web.GetList(listUrl);
                   SPListItemCollection items = list.GetItems(query);
                   // Print a report header.
                   Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                      "Assigned To", "Task", "Due Date", "Priority");
                   // Print the details.
                   foreach (SPListItem item in items)
                      Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                         item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);


    Best Regards

    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact

    Tuesday, January 10, 2017 5:57 AM