-1

I am getting below error :-

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Data.DataRowExtensions.Field<T>(...) returned null.

There are two data tables and I am looping one data table dtExcelResoonse and finding value from another data table dtSqlResponse

var res = from row in dtSqlResponse.AsEnumerable()
                      where (row.Field<string>("RegionCode").ToLower().Trim() ==Convert.ToString(dtExcelResoonse.Rows[k]["RegionCode"]).ToLower().Trim()
                      && row.Field<string>("SectorSubSectorType").ToLower().Trim() == Convert.ToString(dtExcelResoonse.Rows[k]["SectorSubSectorType"]).ToLower().Trim()

dtSqlResponse having null values for Region Code.

F11
  • 3,703
  • 12
  • 49
  • 83
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman Dec 19 '18 at 17:55

1 Answers1

1

You already posted the problem within your last sentence 'dtSqlResponse having null values for Region Code'.

Consinder the following:

string foo = null;
string bar = foo.ToLower(); // throws NULL ref

You will need to check for either: row.Field<string>("RegionCode") != null

or (shortend):

fieldA == null && fieldB == null || fieldA.ToLower().Trim() == fieldB.ToLower().Trim().

Depends on your disired output - you'll need to adjust this query.

nilsK
  • 4,323
  • 2
  • 26
  • 40