Home > Blockchain >  Using an if statement to exclude a null date
Using an if statement to exclude a null date

Time:10-22

I have a DataTable that has a date field within it. I am trying to loop through it and put the value in the date field into a variable.

However when ever it is null the oosDate = Convert.ToDateTime(dt.Rows[0][0]); part causes an error.

So i tried to wrap it in an if statement as shown below that checks in the fields value is null before if carries out the function. It doesnt work though and still carries out the Convert.ToDateTime(dt.Rows[0][0]) function. Can anyone tell me why the != null isnt working?

I have checked the data that is in dt.rows[0][0] when the error occurs and it definitely appears to be null

foreach (DataRow row in dt.Rows)
                    { 
                        if (dt.Rows[0][0] != null )
                        {
                            oosDate = Convert.ToDateTime(dt.Rows[0][0]);
                        }              
                    }

CodePudding user response:

The value is probably DBNull.Value, which... isn't true null (null). Try instead:

if (!dt.Rows[0].IsNull(0))

An alternative would be to try is not DBNull, but IMO the IsNull method encapsulates whatever meaning of null the implementation wants to use, so you don't need to deal with the specifics.

CodePudding user response:

Another way to handle possible null values is to use the Field-extension method:

foreach (DataRow row in dt.Rows)
{ 
    DateTime? oosDateOrNull = row.Field<DateTime?>(0);
    if (oosDateOrNull.HasValue)
    {
        DateTime oosDate = oosDateOrNull.Value;
    }              
}

The Field-method supports nullable types. Use oosDate.HasValue to check if there is a DateTime.

  •  Tags:  
  • c#
  • Related