简体   繁体   English

输入字符串的日期时间格式不正确

[英]Input string was not in a correct format with DateTime

I have a DatePicker from whose value I am trying to insert to an SQL Server table's Date field. 我有一个DatePicker,试图将其值插入SQL Server表的Date字段。

tbl_leave_student updateStdLeave = new tbl_leave_student{
                leave_from=Convert.ToDateTime( dpLeaveFromStd.SelectedDate.GetValueOrDefault())
            };
            db.tbl_leave_students.InsertOnSubmit(updateStdLeave);
            db.SubmitChanges();

This gives a Format Exception with the message 这给出了消息的格式异常

Input string was not in a correct format 输入的字符串格式不正确

I've tried inserting without the Convert.ToDateTime and also dpLeaveFromStd.SelectedDate (without the .GetValueOrDefault()) and got the same error. 我试过不使用Convert.ToDateTimedpLeaveFromStd.SelectedDate (without the .GetValueOrDefault())插入,并得到相同的错误。 Any reason why? 有什么原因吗?

你可以做如下

leave_from = dpLeaveFromStd.SelectedDate ?? DateTime.Now;

you should always use D ateTime.TryParseExact . 您应该始终使用DateTime.TryParseExact

string[] formats = { "dddd, dd MMMM yyyy" };  //your format here
DateTime dt;
if (DateTime.TryParseExact(dpLeaveFromStd.SelectedDate.GetValueOrDefault(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{

}

I guess you are using a Nullable DatePicker and probably you would be getting a null value, 我猜您正在使用Nullable DatePicker,并且可能会得到一个null值,

So you should try to modify the code as 因此,您应该尝试将代码修改为

leave_from = dpLeaveFromStd.SelectedDate.GetValueOrDefault(DateTime.Now);

So this would set it to a default to Today if the value is null 因此,如果该值为null,则将其设置为默认值Today。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM