我有下面的代码无效的转换日期时间?
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);
}
}
}
然而,日期时间的一类?剧组失败并带有“无效投射”。 我检查了SQL数据库和该字段存储有效日期 所以我不能解决为什么,因为我通过DataReader将信息提取到我的应用程序中,日期时间字段导致无效投射。
请帮助。
'caseReader'持有什么类型? – ChrisF 2012-03-29 12:30:04
你的DateTime字段中的一个可能包含一个DBNull - 据我所知,你不能直接从DBNull转换为Nullable类型。然而,这种情况下有扩展。 – Alex 2012-03-29 12:32:06
除了关于空值的其他答案 - 您说该字段正在存储有效日期,但它是否使用适当的数据类型(例如'datetime','datetime2'或'date')来存储它们? – 2012-03-29 12:35:09