0

Have checked the other solutions Object cannot be cast from DBNull to other types, Object cannot be cast from DBNull to other types, though they did not help in my case.

Sample Code:

private void DisplayClosedIncidents()
{
    lstIncidents.Items.Add(new ListItem("--Select an incident--", "None"));
    foreach (DataRowView row in incidentsTable)
    {
        Incident incident = new Incident();
        incident.IncidentID = Convert.ToInt32(row["IncidentID"]);
        incident.ProductCode = row["ProductCode"].ToString();
        incident.DateClosed = Convert.ToDateTime(row["DateClosed"]);
        incident.Title = row["Title"].ToString();
        lstIncidents.Items.Add(new ListItem(incident.CustomerIncidentDisplay(), incident.IncidentID.ToString()));
    }
}

The line in the code causing the error is
incident.DateClosed = Convert.ToDateTime(row["DateClosed"]);

I understand why I'm encountering the error (the value of DateClosed (format is standard yyyy-mm-dd hh:mm:ss) for this row of my DataSource is DBnull, which can't be converted to a DateTime.

I understand I can use default values in the DataSource to resolve the error. Is this the most simple method to resolve? Is there another method I can use to omit this field for the row (keep the null value while retaining the other fields that are not null)?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Christian R
  • 293
  • 2
  • 10
  • 7
    You will have to explicitly check for DBNull, something like `row["DateClosed"] is DBNull ? (DateTime?)null : Convert.ToDateTime(...)`. – Lasse V. Karlsen Apr 25 '22 at 06:48
  • Thanks for your pointer, it was helpful. I solved my problem like so: if (row["DateClosed"].GetType() == typeof(DBNull)) {incident.DateClosed = Convert.ToDateTime("0001-01-01 00:00:00");} – Christian R Apr 26 '22 at 02:31

0 Answers0