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