2014-02-25 120 views
1

插入值,我有这个语法对我的程序:从字符串转换日期和/或时间时转换失败。从的DateTimePicker

con.Open(); 
SqlCommand cmdInsert = new SqlCommand(); 
cmdInsert.Connection = con; 
cmdInsert.CommandText = 
"INSERT INTO Customers VALUES (@Firstname, @LastName, @Birthdate)"; 
cmdInsert.Parameters.Add("@Firstname", SqlDbType.VarChar).Value = txtFirstname.Text; 
cmdInsert.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text; 
cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.DateTime).Value = dtpBirthdate.Value; 

每当执行这段代码,我得到的错误

“转换,从性格 转换日期和/或时间时失败字符串“

我猜测问题根源于”dtpBirthdate.Value“语法。我试图寻找这部分语法的正确格式,但我从来没有幸运。

附加信息:

我也改变dtpBirthdate.ValueDBNull.Value和它产生同样的错误。

回答

2

使用返回的日期时间的日期属性:

dateTimePicker1.Value.Date 
0

尝试DateTime.Parse(dtpBirthdate.Value)

0
cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.String).Value = dtpBirthdate.Value; 
+0

请添加一些关于您的代码的具体描述。它有助于人们更好地理解您的解决方案。 – Rachcha

+0

我的意思是请编辑你的答案并添加你的描述。此外,添加说明和更多混淆的代码。 – Rachcha

0

试试这个:

cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.DateTime).Value = 
       dtpBirthdate.Value.ToString("yyyy-MM-ddTHH:mm:ss"); 
1

我解决它。我的代码有什么问题是我的insert语句中参数变量的顺序。它应该匹配我数据库中列的顺序。

相关问题