0

I 'm getting this error: An unhandled exception of type "System.NullReferenceException' occurred in DataReport.exe" in the linq query. Hereafter my code. Any idea how to handle this exception. Thanks.

private void btnFilterBy_Click(object sender, EventArgs e)
{
    var records = 
        from record in data.AsEnumerable()
        where (record.Field<string>(data.Columns[0].ColumnName).Contains(txtBC.Text) && 
               record.Field<string>(data.Columns[1].ColumnName).Contains(txtRM.Text) &&
               record.Field<string>(data.Columns[2].ColumnName).Contains(txtClient.Text) &&
               record.Field<string>(data.Columns[4].ColumnName).Contains(txtProduct.Text) &&
               record.Field<string>(data.Columns[7].ColumnName).Contains(txtSegment.Text) &&
               record.Field<string>(data.Columns[6].ColumnName).Contains(txtMonth.Text))
        select record;
    dataQuery = records.CopyToDataTable();
    dtGridPivot.DataSource = dataQuery;
}
RB.
  • 33,692
  • 12
  • 79
  • 121
user2738335
  • 57
  • 1
  • 8

2 Answers2

1

The error indicates one or more of the fields you are requesting are missing. This is probably due to either the data object being null, or one of the Columns missing.

Try adding something like the following lines of code

if (data == null)
   throw new InvalidOperationException("Data is null");

if (data.Columns.Count < 8)
   throw new InvalidOperationException("Invalid number of columns.");

// Casting as DataColumn - but cast as whatever is approperiate
if (data.Columns.Cast<DataColumn>().Any(x => x == null || x.ColumnName == null))
    throw new InvalidOperationException("Data values are missing or null.");


var records = 
    from record in data.AsEnumerable()
    where (record.Field<string>(data.Columns[0].ColumnName).Contains(txtBC.Text) && 
           record.Field<string>(data.Columns[1].ColumnName).Contains(txtRM.Text) &&
           record.Field<string>(data.Columns[2].ColumnName).Contains(txtClient.Text) &&
           record.Field<string>(data.Columns[4].ColumnName).Contains(txtProduct.Text) &&
           record.Field<string>(data.Columns[7].ColumnName).Contains(txtSegment.Text) &&
           record.Field<string>(data.Columns[6].ColumnName).Contains(txtMonth.Text))
    select record;
dataQuery = records.CopyToDataTable();
dtGridPivot.DataSource = dataQuery;

This will ensure that the column values being loaded, exist or throws a more meaningful exceptions.

Kami
  • 18,269
  • 4
  • 43
  • 62
  • I used the code, it doesn' catch the exception the compiler does, same as the first one. I'v checked again the data (origin file excel), there was 2 values missed ! from 29644 lines. – user2738335 Sep 10 '13 at 14:39
0

I traditionally use the null coellescing operator ?? to check for nulls in my collections and where expressions to filter before selection, grouping or ordering

Gusdor
  • 13,036
  • 2
  • 47
  • 60