我使用以下代码从文本框中保存日期并使用日期选择器选择日期。
If (String.IsNullOrEmpty(DobTxt.Text)) Then
SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DBNull.Value
Else
Dim DOBDte As date= String.Format("{0:YYYY-MM-dd}", DobTxt.Text.Trim())
SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DOBDte
End If
现在代码可以正常处理像 ""这样的日期
但是当你选择“10/01/2016”之类的日期时,我会收到此错误:
从字符串“10/30/2016”到类型“Date”的转换无效
你能帮忙吗
最佳答案
使用 TryParse
将文本值转换为日期。
Dim dateValue As Date
If String.IsNullOrWhiteSpace(DobTxt.Text) Then
SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DBNull.Value
ElseIf Date.TryParse(DobTxt.Text.Trim(), dateValue) Then
SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = dateValue
Else
' alert the user that there is invalid input
End If
关于sql - 使用 vb.net 在 SQL 中保存日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264886/