0

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?

1
  • Just add null checks where you suspect them. for example r.Field<string>("ContractPOReference != null ... Commented Jul 13, 2012 at 11:25

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Exception occurred "Can not create DataView after using projection".On line DT = query.AsDataView().ToTable();
You can do this also with linq methods like r.Field<string>("ContractPOReference") != null && r.Field<string>("ContractPOReference").ToUpper().Contains(text.ToUpper()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.