如何解决如何使用asp.net 3层体系结构在数据库中插入空日期值
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
解决方法
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())
如果objChildFees.withdrawaldate
为空,则可以将其设置为nullable DateTime。在尝试将其转换为txtwtdate.Text
之前,请检查DateTime?
的值
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
的值在转换时包含有效的日期字符串,以避免在转换过程中引发异常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。