Invalid Date DateTime?

I have a class with the following code

 public cCase(string pCaseNo, string pMode)
    {
        if (pMode == "new")
        {
            this._caseNo = Validate_CaseNo(pCaseNo);
        }
        if (pMode == "existing")
        {
            try
            {
                int intValidatedCaseNo = Validate_CaseNo(pCaseNo);
                string sqlText = "SELECT * FROM tblCases WHERE CaseNo = @CaseNo;";
                string strConnection = cConnectionString.BuildConnectionString();
                SqlConnection linkToDB = new SqlConnection(strConnection);
                linkToDB.Open();
                SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
                sqlCom.Parameters.Add("@CaseNo", SqlDbType.Int);
                sqlCom.Parameters["@CaseNo"].Value = intValidatedCaseNo;
                SqlDataReader caseReader = sqlCom.ExecuteReader();
                if (caseReader.HasRows)
                    while (caseReader.Read())
                    {
                        this._claimant = caseReader["Claimant"].ToString();
                        this._defendant = caseReader["Defendant"].ToString();
                        this._caseType = caseReader["CaseType"].ToString();
                        this._occupation = caseReader["Occupation"].ToString();
                        this._doa = (DateTime?)caseReader["DOA"];
                        this._dateClosed = (DateTime?)caseReader["DateClosed"];
                        this._dateSettled = (DateTime?)caseReader["DateSettled"];
                        this._dateInstructed = (DateTime?)caseReader["DateInstructed"];
                        this._status = caseReader["Status"].ToString();
                        this._instructionType = caseReader["InstructionType"].ToString();
                        this._feeEstimate = (decimal?)caseReader["FeeEstimate"];
                        this._amountClaimed = (decimal?)caseReader["AmountClaimed"];
                        this._amountSettled = (decimal?)caseReader["AmountSettled"];
                        this._caseManager = caseReader["CaseManager"].ToString();
                    }
                caseReader.Close();
                linkToDB.Close();
                linkToDB.Dispose();
            }
            catch (Exception eX)
            {
                throw new Exception("Error finding case" + Environment.NewLine + eX.Message);
            }
        }
    }

      

However Datetime? cleared from "Invalid Cast". I checked the SQL database and the field is storing valid dates So I cannot figure out why, since I am fetching information via DataReader into my application, datetime fields are calling Invalid Cast.

Please, help.

+3


source to share


6 answers


You want to change the line that reads:

this._doa = (DateTime?)caseReader["DOA"];

      

in



if (caseReader["DOA"] != DBNull.Value)
    this._doa.Value = (DateTime)caseReader["DOA"];

      

Like all similar lines.

DBNull values ​​cannot be selected from Nullable types.

+7


source


The fields DateTime

probably contain a value DBNull

that you cannot directly convert.

However, for convenience, I would use an extension method on yours DataReader

.

public static class DataReaderExtensions
{
  public static DateTime? ReadNullableDateTime(this IDataReader reader, string column)
    {
        return reader.IsDBNull(column) ? (DateTime?)null : reader.GetDateTime(column);
    }
}

      



//Using

 this._dateInstructed = CaseReader.ReadNullableDateTime("DateInstructed");

      

+4


source


You must use

DateTime.TryParse Method

this is no exception, for example

var mydate =(DateTime)datetimeString

      

or var mydate = DateTime.Parse (datetimeString)

does !!!

+2


source


Try the following piece of code

this._doa = (caseReader["DOA"] == DBNull.Value ? DBNull.Value : Convert.ToDateTime(caseReader["DOA"]); 

      

0


source


Try to convert your date time like

this._doa = Convert.ToDateTime(caseReader["DOA"]);

      

0


source


I often practice DBNull.Value

...

Therefore I use this method which will return the object value or default value for the given value type if the object value DBNull.Value

.

    public static object GetValueOrDefault(object value, Type type)
    {
        if (value != DBNull.Value)
            return value;

        if (type.IsValueType == false)
            return null;

        Array array = Array.CreateInstance(type, 1);

        return array.GetValue(0);
    }

      

Using:

GetValueOrDefault(dataRecord.GetValue(fieldIndex), dataRecord.GetFieldType(fieldIndex)

      

0


source







All Articles