Limna
Limna

Reputation: 403

What can be assigned in bool and DateTime variables in case of null?

DataTable rdrFeedback;
using (rdrFeedback = CommonHelper.GetDataTable(CommandType.StoredProcedure, "[Crew].[Up_CM_SEAFARER_FEEDBACK]", sqlParams.ToArray()))
{
    foreach(DataRow dRow in rdrFeedback.Rows)
    {
            bool? AnswSix = dRow["ANSW_SIX"] != DBNull.Value ? (bool)dRow["ANSW_SIX"] : DBNull.Value; 
            DateTime? AcknowledgedOn = dRow["ACKNOWLEDGED_ON"] != DBNull.Value ? Convert.ToDateTime(dRow["ACKNOWLEDGED_ON"].ToString()) : null;
    }
}

Above statement gives this errors while fetching data from stored procedure:

Type of conditional expression cannot be determined because there is no implicit conversion between 'bool' and 'System.DBNull'.

Type of conditional expression cannot be determined because there is no implicit conversion between 'DateTime' and 'null'.

Upvotes: 0

Views: 218

Answers (1)

Igor
Igor

Reputation: 62318

Add a cast to DateTime? from DateTime

DateTime? AcknowledgedOn = dRow["ACKNOWLEDGED_ON"] != DBNull.Value 
   ? (DateTime?) Convert.ToDateTime(dRow["ACKNOWLEDGED_ON"].ToString()) 
   : null;

The same is true for bool but you have to specify null as the alternate value not DBNull.Value.

bool? AnswSix = dRow["ANSW_SIX"] != DBNull.Value 
  ? (bool?)dRow["ANSW_SIX"] 
  : null; 

Also why are you using Convert.ToDateTime? If your database has a date time value it should be:

  1. Stored as an actual Date or DateTime type in the database
  2. Retrieved as a DateTime type

Do not store DateTime instances as strings and do not retrieve them as strings.

Upvotes: 1

Related Questions