【发布时间】:2018-05-30 04:58:43
【问题描述】:
我的应用中有 3 个文本框。第三个是出生日期,用户可以留空。
应用程序将用户输入的值保存到 SQL Server 数据库中,该数据库具有一个包含 3 列的表。生日列的数据类型设置为Date,并定义为可为空。
如果用户将生日文本框保留为空,我想将 NULL 分配到 birthday 列中,所以我尝试了以下代码:
If txtBirthday.Text = "" Then
command.Parameters.AddWithValue("@Field3", DBNull.value)
End If
但这没有用。我也试过(添加Imports System.Data.SqlTypes后):
If txtBirthday.Text = "" Then
command.Parameters.AddWithValue("@Field3", SqlDateTime.Null)
End If
但这也没有用。
我寻找解决问题的方法,但没有成功。
请帮忙
这是我的完整代码:
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
这是我得到的例外:
{System.Data.SqlClient.SqlError: 转换时转换失败 字符串中的日期和/或时间。}
【问题讨论】:
-
看起来应该可以了。你能告诉我们存储过程或命令文本吗?
-
文本框有遮罩吗?...真的是空的吗?找出替换空格的值以验证它是否真的为空白
-
笑着试试 cmd.Parameters.Add("@Field3", SqlDbType.Date).Value = DBNull.Value
-
(N0Alias) - 我更新了我的问题,包括命令文本......(约翰凯恩) - 不,它没有任何掩码......(玛丽) - 尝试了你的建议,但没用。它给出了同样的例外
标签: asp.net sql-server vb.net datetime nullable