gpt4 book ai didi

c# - 无效的转换日期时间?

转载 作者:行者123 更新时间:2023-11-30 13:17:22 26 4
gpt4 key购买 nike

我有一个包含以下代码的类

 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 将信息提取到我的应用程序中时,日期时间字段导致无效转换。

请帮忙。

最佳答案

您将要更改以下行:

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

到:

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

以及所有类似的行。

DBNull 值不能从 Nullable 类型转换。

关于c# - 无效的转换日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com