Avoid Null value exception in LINQ

I'm trying to filter a DataTable using LINQ

DataTable DT=new DataTable();
DT = PinDicDAO.GetContractPOVD().AsEnumerable().Where(r => (r.Field<string>("ContractPOReference").ToUpper().Contains(text.ToUpper())) || (r.Field<string>("ContractPO").ToUpper().Contains(text.ToUpper())) ||
                                   (r.Field<string>("ContractPOTitle").ToUpper().Contains(text.ToUpper())) || (r.Field<string>("Address").ToUpper().Contains(text.ToUpper()))

Query works fine. But when some fields have NULL values it gives a Exception.

"Object Reference Not set to an instance of object"

How can I avoid this exception?


Check for nulls before you try to use it. You'd better use the linq keywords so you can use let and make it more readable:

var query = from r in PinDicDAO.GetContractPOVD().AsEnumerable()
                        let ContractPOReference = r.Field<string>("ContractPOReference")
                        let ContractPO = r.Field<string>("ContractPO")
                        let ContractPOTitle = r.Field<string>("ContractPOTitle")
                        let Address = r.Field<string>("Address")
                        where (ContractPOReference != null && ContractPOReference.ToUpper().Contains(text.ToUpper())) ||
                           (ContractPO != null && ContractPO.ToUpper().Contains(text.ToUpper())) ||
                           (ContractPOTitle != null && ContractPOTitle.ToUpper().Contains(text.ToUpper())) ||
                           (Address != null && Address.ToUpper().Contains(text.ToUpper()))
                        select r;

            DT = query.AsDataView().ToTable();

Need Your Help

Rails partial iframe missing assets

ruby-on-rails ruby iframe partial-views assets

I'm trying to create an iframe that's placed on an other website (not mine) and renders one partial of my site. Everything works well but the content of the iframe (my site) doesn't seem to have any

Calling Controller Function in Ajax

javascript c# jquery asp.net ajax

I want to call this yellow colored Controller function with ajax (Image of my project).