chamara
chamara

Reputation: 12709

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()))
                                   ).AsDataView().ToTable();

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?

Upvotes: 0

Views: 1551

Answers (1)

Amiram Korach
Amiram Korach

Reputation: 13286

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();

Upvotes: 1

Related Questions