I have 3 textboxes in my app. the 3rd one is for date of birth which user can keep empty.
The app saves the values entered by the user into a SQL Server database that has a table with 3 columns. The birthday column's datatype is set to Date
and it is defined as nullable.
If the user keeps the birthday textbox empty, I want to assign NULL into the birthday
column, so I tried this code:
If txtBirthday.Text = "" Then
command.Parameters.AddWithValue("@Field3", DBNull.value)
End If
But that didn't work. I also tried (after adding Imports System.Data.SqlTypes
):
If txtBirthday.Text = "" Then
command.Parameters.AddWithValue("@Field3", SqlDateTime.Null)
End If
But that also didn't work.
I looked for a solution for the problem, but no success.
Please help
Here Is my full code:
Dim Query As String = "INSERT INTO UserInfo (fName, lName, bDay) VALUES (@Field1, @Field2, @Field3);"
Dim connectionString = ConfigurationManager.ConnectionStrings("myapp_con_string").ConnectionString
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(Query, connection)
With command
.Connection = connection
.CommandType = CommandType.Text
.CommandText = Query
.Parameters.AddWithValue("@Field1", txtFirstname.Text)
.Parameters.AddWithValue("@Field2", txtLastname.Text)
If txtBirthday.Text = "" Then
command.Parameters.AddWithValue("@Field3", DBNull.value)
Else
command.Parameters.AddWithValue("@Field3", Convert.ToDateTime(txtBirthdat.Text).ToString("yyyy/MM/dd"))
End If
End With
Try
connection.Open()
command.ExecuteNonQuery()
lblMessages.Text = "Data Saved"
Catch ex As SqlException
lblMessages.Text = "Data Not Saved"
End Try
End Using
This is the exception I got:
{System.Data.SqlClient.SqlError: Conversion failed when converting date and/or time from character string.}