Sujit.Warrier
Sujit.Warrier

Reputation: 2869

Object reference not set to an instance of an object. yet foreach loop is working

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

Upvotes: 0

Views: 1946

Answers (4)

Sujit.Warrier
Sujit.Warrier

Reputation: 2869

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

Upvotes: 0

Dah Sra
Dah Sra

Reputation: 4425

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

 var productdata = dt.Select("Edited='NEW'");

Upvotes: 1

Luke Stoward
Luke Stoward

Reputation: 1540

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.

Upvotes: 1

Lee
Lee

Reputation: 144126

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.

Upvotes: 4

Related Questions