2013-07-29 40 views
0

到SQL Server 2008,我得到failed to convert parameter value from a string to a datetime錯誤,我有哪些用戶應插入日期的文本框,我的代碼是:插入日期時間使用C#

SqlConnection Con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); 
SqlDataAdapter adapt = new SqlDataAdapter(); 
adapt.InsertCommand = new SqlCommand("INSERT INTO tblEmployee VALUES (@employeeNumber, @employeePrivateName, @employeeFamilyName ,@city, @street, @houseNo, @phoneNumber, @birthDate, @startWorkingDate)", Con); 
adapt.InsertCommand.Parameters.Add("@employeeNumber", SqlDbType.VarChar).Value = textBox1.Text; 
adapt.InsertCommand.Parameters.Add("@employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text; 
adapt.InsertCommand.Parameters.Add("@employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text; 
adapt.InsertCommand.Parameters.Add("@city", SqlDbType.VarChar).Value = textBox4.Text; 
adapt.InsertCommand.Parameters.Add("@street", SqlDbType.VarChar).Value = textBox5.Text; 
adapt.InsertCommand.Parameters.Add("@houseNo", SqlDbType.Int).Value = textBox6.Text; 
adapt.InsertCommand.Parameters.Add("@phoneNumber", SqlDbType.VarChar).Value = textBox7.Text; 
adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = textBox8.Text; 
adapt.InsertCommand.Parameters.Add("@startWorkingDate", SqlDbType.DateTime).Value = textBox9.Text; 

Con.Open(); 
adapt.InsertCommand.ExecuteNonQuery(); 
Con.Close(); 

我如何得到它的工作?

+1

那麼你有什麼文字試圖轉換爲'DateTime'? –

+0

日期格式爲2000/05/22,例如 – user2023203

+0

默認爲'yyyy-MM-dd hh-mm-ss' –

回答

2

我想這個問題是在這裏:

adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = textBox8.Text; 

您指定類型爲DateTime類型和你傳遞一個字符串。試試你的字符串值轉換爲DateTime類型的對象,如:

adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value 
     = Convert.ToDateTime(textBox8.Text); 

,你可以看看到DateTime.ParseExactDateTime.TryParseExact,如果在分析過程中獲得格式異常。參見:​​。

+1

'AddWithValue'使用字符串而不是'DateTime'。一個簡單的'DateTime.Parse(「2013/05/22」)'應該工作(或更好的'TryParse ...)'。 –

+0

@TimSchmelter,刪除那部分:),我不確定它 – Habib

+0

謝謝,但是當我使用你的解決方案時,我得到「字符串或二進制數據將被截斷,語句已被終止。 – user2023203

0

你可以在adapt.InsertCommand最好設置爲一個變量,並用它來代替(包括逆足少打字)

假設你擔保的文本框的文本格式正確,更改與日期時間參數,如線這

adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = DateTime.Parse(textBox8.Text, "yyyy/MM/dd");