[英]Input string was not in a correct format with DateTime
我有一個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();
這給出了消息的格式異常
輸入的字符串格式不正確
我試過不使用Convert.ToDateTime
和dpLeaveFromStd.SelectedDate (without the .GetValueOrDefault())
插入,並得到相同的錯誤。 有什么原因嗎?
你可以做如下
leave_from = dpLeaveFromStd.SelectedDate ?? DateTime.Now;
您應該始終使用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))
{
}
我猜您正在使用Nullable DatePicker,並且可能會得到一個null值,
因此,您應該嘗試將代碼修改為
leave_from = dpLeaveFromStd.SelectedDate.GetValueOrDefault(DateTime.Now);
因此,如果該值為null,則將其設置為默認值Today。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.