0

so im having a weird problem. when i make a linq query on a datatable I get

"Object reference not set to an instance of an object."

but when a use forloop on the result it works correctly.dt is a datatable

var productdata = from data in dt.AsEnumerable() 
                  where data.Field<string>("Edited").ToString().ToUpper() == "NEW"
                  select data;//I get the object reference error here

foreach (var item in productdata) //but here the control goes inside the foreachloop even though the object refrence was null and the code gets executed correctly
{
   //operation
}

only after the last iteraton does it give the null reference exception again. I dont understand why this is happening

Sujit.Warrier
  • 2,815
  • 2
  • 28
  • 47

4 Answers4

4

The items in productdata are produced lazily, and the exception probably occurs in the Where clause:

where data.Field<string>("Edited").ToString().ToUpper() == "NEW"

the productdata sequence is not null so the foreach can begin executing, but the exception will not be thrown until MoveNext is called and the Edited field is accessed and found to be null.

Lee
  • 142,018
  • 20
  • 234
  • 287
1

Update your linq query as follows:

var productdata = (from data in dt
                  where data.Field<string>("Edited").ToString().ToUpper() == "NEW"
                  select data)
                  .ToList();//I get the object reference error here

This will return the results set immediately, and validate the foreach loop.

Luke Stoward
  • 1,480
  • 14
  • 24
  • when i do tolist im instantly getting exception "Object reference not set to an instance of an object." – Sujit.Warrier Feb 17 '16 at 09:44
  • @Mysterio11 why youre converting it into var , try getting it in datarow by using dt.select(); – Dah Sra Feb 17 '16 at 09:45
  • @Mysterio11 I would suggest checking that 'dt' (assuming thats your dbContext.dt) is not null before attempting to build the linq query. – Luke Stoward Feb 17 '16 at 09:51
1

Why use of linQ here where you can simply get your output by using

 var productdata = dt.Select("Edited='NEW'");
Dah Sra
  • 4,107
  • 3
  • 30
  • 69
0

I found the answer. you see i was creating this datatable by reading an excel file. and in the file only one row had "NEW" in the edited column. the rest were empty. As soon as i put dummy values in the rest of the rows it started working perfectly. Donno why this is happening but at least got my code to work

Sujit.Warrier
  • 2,815
  • 2
  • 28
  • 47