【问题标题】:how to insert null date value in database using asp.net 3 tier architecture如何使用 asp.net 3 层架构在数据库中插入空日期值
【发布时间】:2020-08-20 13:59:33
【问题描述】:
if (objChildFees.childid != null)
{
        objChildFees.classstudentid = 0;
        objChildFees.classid = Convert.ToInt16(ddlClass.SelectedValue);
        objChildFees.centerid = Convert.ToInt32(Session[CommonVariables.gCentreId].ToString());
        objChildFees.roomno = 1;
        objChildFees.startdate = Convert.ToDateTime(txtStartDate.Text.ToString());
        objChildFees.enddate = Convert.ToDateTime(txtEndDate.Text.ToString());
        objChildFees.newfees = Convert.ToDecimal(txtfeesamt.Text.ToString());
        objChildFees.feestype = chkFeesPay.Checked == true ? 1 : 2;
        objChildFees.childdaystype = chkfulltime.Checked == true ? 1 : 2;
        objChildFees.feepermonthforsubsidized = 0;
        objChildFees.feepermonthforpartime = 0;
        objChildFees.feepermonthforparttimesubsidized = 0;
        objChildFees.activestatus = true;
        objChildFees.withdrawaldate = Convert.ToDateTime(txtwtdate.Text);
}

如何在此代码中添加空提款日期我面临错误:String was not recognized as a valid DateTime

【问题讨论】:

  • 指定IFormatProvider。或者使用指定格式的DateTime.ParseExact 方法。

标签: asp.net datetime


【解决方案1】:

如果objChildFees.withdrawaldate 可以为空,则可以将其设置为nullable DateTime。在尝试将其转换为 DateTime? 之前检查 txtwtdate.Text 的值

public class ChildFees 
{
  // The ? after DateTime indicates this variable should be a nullable datatype
  DateTime? withdrawldate {get; set;}
  ...
}

objChildFees.withdrawaldate = string.IsNullOrWhiteSpace(txtwtdate.Text) ? null : (DateTime?)Convert.ToDateTime(txtwtdate.Text);

在生产系统中,您可能希望在转换时使用DateTime.TryParse 来确保txtwtdate.Text 的值包含有效的日期字符串,以避免在转换过程中引发异常。

【讨论】:

  • 我尝试过这个但显示错误:无法确定条件表达式的类型,因为 之间没有隐式转换
  • @HarshPatel 那是因为Convert.ToDateTime() 的输出是DateTime,而不是DateTime?。您需要将结果转换为DateTime?,如下所示:(DateTime?)Convert.ToDateTime(txtwtdate.Text)
  • 也尝试了此代码,但没有结果错误是:SqlException (0x80131904):过程或函数“Sp_InsertUpdateChildEnrollmentFeesDetails”需要参数“@withdrawaldate”,但未提供。]
  • @HarshPatel 您收到该错误是因为您没有将@withdrawldate 作为参数提供给您的存储过程。您可以在存储过程中为 @withdrawldate 提供默认值 null,或者确保始终将 @withdrawldate 作为参数传递,其值为 null 或实际日期。您需要确保您的数据库字段也设置为允许空值。
【解决方案2】:
public static class Extenstions
{
    public string ToNullableString(this string value)
    {
         if (string.IsNullOrEmpty(value))
         {
             return null;
         }
         
         return value;
     }
}

确保withdrawaldate 属性具有可为空的类型(DateTime?

然后这样使用Convert.ToDateTime(txtwtdate.Text.ToNullableString())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 2016-05-19
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多