0

I have a DataTable called dtMondayNewsLetter and when the DT returns no rows. i.e. Empty

it shows an error Object reference not set to an instance of an object

CODE

CurrentDirection = Convert.ToString((from DataRow dr in dtMondayNewsLetter.Rows 
                    where (int)dr["PostID"] == PostID select (string)dr["Direction"])
                           .FirstOrDefault()).Trim();

What changes I need to do in above code to eliminate the error.

Rahul Singh
  • 20,580
  • 5
  • 32
  • 49

3 Answers3

3

As you mentioned, query

from DataRow dr in dtMondayNewsLetter.Rows 
where (int)dr["PostID"] == PostID 
select (string)dr["Direction"]

returns no rows, so FirstOrDefault() returns null.

so you can do a simply if to check wheter result is available..

var resultString = (from DataRow dr in dtMondayNewsLetter.Rows
                    where (int)dr["PostID"] == PostID 
                    select (string)dr["Direction"])
                   .FirstOrDefault();

if (resultString != null) 
{
    CurrentDirection = resultString.Trim();
}
else
{
    //case, when no rows
}
pwas
  • 3,087
  • 14
  • 36
1

To expand on my comment, I would do something like:

foreach (DataRow dr in dtMondayNewsLetter.Rows)
{
    if (dr["PostID"] != DBNull.Value && dr["Direction"] != DBNull.Value)
    {
        if ((int)dr["PostID"] == PostID)
        {
            CurrentDirection = dr["Direction"].ToString();
        }
    }
}

Trying to be concise by shoving everything into a LINQ statement is not always optimal. In your case, there could be a number of objects, or data, which is NULL, thus causing the null reference exception exception.

Inside a one line LINQ statement, it's very difficult to figure out where the NULL object is. Splitting that LINQ statement into a for...each loop makes things a lot easier, and achieves the exact same result.

However, if "PostID" and "Direction" are non-nullable (thus no need to use DBNull.Value checks), then use @nopeflow answer, as that is much safer then your current implementation.

Jason Evans
  • 28,042
  • 13
  • 88
  • 145
0

You can use Null-Coalescing Operator. in case that FirstOrDefault returns null return empty string.

CurrentDirection =
    Convert.ToString(
        (from DataRow dr in dtMondayNewsLetter.Rows
            where (int) dr["PostID"] == PostID
            select (string) dr["Direction"]).FirstOrDefault() ?? "").Trim();
M.kazem Akhgary
  • 16,678
  • 6
  • 49
  • 100