Celtic Coding Solutions Blog

Celtic Coding Solutions Blog - for everything computer related

Linq NullReferenceException on Where Clause

Had a strange error when running a similar query taking data from SQL Server:-

 var returnData = from selectedData in dataTable.AsEnumerable()

 where selectedData.Field<string>("ProductCategory").Trim().ToUpper() == all about abortion "CAT1"

 select selectedData

 

Error was:-

NullReferenceException abortion pill info was unhandled - Object reference not set to an instance of an object

And in debugger it was pointing to the where clause.  After lots of looking around it was because the field "ProductCategory" being returned from SQL Server was returning some nulls in the data.

The Fix:-

Use the ?? operator (see http://msdn.microsoft.com/en-us/library/ms173224.aspx)

var returnData = from selectedData in dataTable.AsEnumerable()

where (selectedData.Field<string>("ProductCategory") ?? "").Trim().ToUpper() == "CAT1"

select selectedData

 

Comments are closed