【问题标题】:Date time still thinking its null even though I have set its nullable value即使我设置了它的可为空值,日期时间仍然认为它是空的
【发布时间】:2016-03-06 23:04:35
【问题描述】:

我正在尝试创建一个实体对象,但我的日期有一些问题,它声称它没有值,即使我已将空白日期设置为 1900。

DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

下面是使用它的保存函数。

    int id = Convert.ToInt32(Request.QueryString["id"]);


    _appointment = _dal.GetAppointMentByiD(id ,"");

    _appointment.CustomName = txtCustomerName.Text;
    DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

    DateTime endDate = rdEndDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdEndDate.SelectedDate.Value;

    _appointment.Start = startDate;
    _appointment.End = endDate;
    _appointment.Subject = txtSubject.Text;

    _appointment.notes = txtNotes.Text;
    _appointment.preferedContactNumber = txtContactNum.Text;
    _appointment.mobileNumber = txtMobileNumber.Text;
    _appointment.authUserName = Environment.UserName;
    _appointment.authCreatedDate = DateTime.Now;
        if (id == 0)
        {
            _dal.AddApointments(_appointment);
        }
    _dal.SaveChanges();
    rdMessaeBox.RadAlert("Appointment Saved", 200, 100, "Calander", "callBackFn", "myAlertImage.png");
  Response.Redirect("default.aspx");

.net 中的错误是 可空对象必须有一个值。 说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

Exception Details: System.InvalidOperationException: Nullable object must have a value.

【问题讨论】:

  • 如果 rdStarDate.SelectedDate == null ,然后访问 .Value 将抛出该异常。如果不是这种情况,请说明异常发生的确切位置。
  • 是的,使用该值的最佳方法是使用日期的 tryParse ?

标签: c# entity-framework


【解决方案1】:
DateTime startDate = rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1) ? DateTime.Today : rdStarDate.SelectedDate.Value;

这行说:rdStartDate.SelectedDate.Value 正好是1900/1/1,然后(并且只有那时)将startDate 设置为DateTime.Today
如果是null,访问rdStartDate.SelectedDate.Value 将抛出一个InvalidOperationException,其中包含您收到的确切消息!

我想你真正想要的是

DateTime startDate = (!rdStarDate.SelectedDate.HasValue ||
    rdStarDate.SelectedDate.Value == new DateTime(1900, 1, 1)) 
    ? DateTime.Today 
    : rdStarDate.SelectedDate.Value;

您声明您确实rdStarTime.SelectedValue 设置为1900/1/1,但您没有显示该行,也没有显示异常的堆栈跟踪。因此,如果您真的设置了该值,则可能引发异常的唯一其他可能性是您的 rdEndDate.SelectedValue.Value 的同一行。

P.S.:不应该是rdStartDate 而不是rdStarDate吗?

【讨论】:

    猜你喜欢
    • 2022-12-15
    • 2020-11-24
    • 1970-01-01
    • 2022-01-18
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 2021-08-23
    相关资源
    最近更新 更多