Storing date in SQL using vb.net
I am using the following code to store a date from a textbox and select a date using a date picker.
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
Now the code works fine with dates like ""
but when you go to a date like "01/10/2016" I get this error:
Conversion from string "10/30/2016" to input "Date" is not valid
Could you help me?
+3
source to share
2 answers
Use TryParse
to convert a text value to a date.
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
+2
source to share