Object cannot be cast from DBNull to other types
Use the System.Data.DataRow.IsNull function instead.
if(dr.IsNull("Stage"))
{
...
}
Use ==
instead of is
if (dr["STAGE"] == DBNull.Value)
{
}
Use this slightly more efficient approach
int stageOrdinal = dr.GetOrdinal("STAGE");
while (dr.Read()) {
dto = new DataTransferObject();
if (dr.IsDBNull(stageOrdinal)) {
dto.Stage = 1;
} else {
dto.Stage = dr.GetInt32(stageOrdinal);
}
//TODO: retrieve other columns.
dtoList.Add(dto);
}
Accessing the columns by their index is faster than accessing them by name. The index of a column can be retrieved with the GetOrdinal
method of the DataReader
. This is best done before the loop.