I am trying to insert a date from a DateTimePicker in a Windows Form in VB.Net into an SQL string in such a way as it recognises it as a datetime (the field itself is set as datetime in SQL Server).
I have tried a few methods (Convert at SQL level, Format at VB.Net level) and am now using a variable stored as DateTime, however I still cannot get it to work. A snippet of my code is below:
Using sqlConn = New SqlConnection(My.Settings.sqlString)
sqlConn.Open()
Dim dte As DateTime = Convert.ToDateTime(Me.dateMain.Text)
Dim cmd As SqlCommand
cmd = sqlConn.CreateCommand
cmd.CommandText = "Update Table1 " &
"SET Person='" & Me.person.Text & "'," &
"Date='" & dte & "' " &
"WHERE (Code = '" & PCode & "')"
cmd.ExecuteNonQuery()
cmd = Nothing
End Using
EDIT: The following error (or slight variation of) is what I have got with almost every attempt I have tried. This error was received after the Parameterization answer submitted below
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
So it seems that even still, it is not recognising it as a datetime in SQL. I imagine I will need to try again with Convert in the SQL string, but my knowledge of the function is limited. Anyone know how I can use it to get this to work (if that is the solution)?
DateTimePickercontrol in Windows Form has a propertyValuewhich returns theDateTimeselected in control. Use this property so you don't need to convertStringintoDateTimeDate=#3/4/12#which didnt work in a connection string, hence my switch to using.Textwhich gives the date in a more recognizable text format for SQL" WHERE (Code = '" & PCode & "')"