2014-01-21 81 views
2

將數據添加到數據庫時,date_to和date_from中出現錯誤。 在sql server數據庫中,date_to的數據類型爲&,date_from是日期。建議一些解決方案從字符串中轉換日期和/或時間時轉換失敗

try 
{ 
    cmd = new SqlCommand("insert into license1 values(@l_id,@customer_id,@d_id,@device_name,@from,@to)", cn); 

    cmd.Parameters.AddWithValue("@l_id", license_id.Text); 
    cmd.Parameters.AddWithValue("@customer_id", c_comboBox4.Text); 
    cmd.Parameters.AddWithValue("@d_id", d_id_comboBox4.Text); 
    cmd.Parameters.AddWithValue("@device_name", d_name_comboBox5.Text); 
    cmd.Parameters.AddWithValue("@to", date_to.Text); 
    cmd.Parameters.AddWithValue("@from", date_from.Text); 

    cn.Open(); 
    a = cmd.ExecuteNonQuery(); 
    if (a > 0) 
    { 
     MessageBox.Show("Data Submitted"); 
    } 

} 
catch (Exception ex) 
{ 
     MessageBox.Show(ex.Message); 
} 
+4

總是發佈確切的錯誤信息。 –

+1

用戶在文本框中輸入的日期格式是什麼? –

回答

0

我認爲你的日期格式可能會導致問題。您必須使用SQL提供程序支持的日期格式。大多數SQL使用MM-dd-yyyy格式。所以如果你通過21-1-2014,SQL服務器不接受它,因爲21個月不存在。

+0

SQL Server中DATETIME的唯一真正的文化不變格式是yyyyMMdd。 – GarethD

6

以轉化成你自己的手中:

cmd.Parameters.AddWithValue("@to", DateTime.Parse(date_to.Text)); 
cmd.Parameters.AddWithValue("@from", DateTime.Parse(date_from.Text)); 

,當仍然失敗,使用一個版本的DateTime.ParseExact()用適當的格式和CultureInfo的。

您可能想要考慮添加更強大和更廣泛的驗證圖層。日期和數字對打字錯誤,用戶設置和用戶假設非常敏感。

總是假設TextBox.Text是充滿了錯誤。

2

試試這個

cmd.Parameters.AddWithValue("@to",Convert.ToDateTime(date_to.Text)); 
cmd.Parameters.AddWithValue("@from",Convert.ToDateTime(date_from.Text}); 
4

如果用戶輸入的日期格式爲:yyyy-MM-dd那就試試這個:

String strDateFormat= "yyyy-MM-dd";//change accordingly if format is something different 
DateTime to=DateTime.ParseExact(date_to.Text,strDateFormat, CultureInfo.InvariantCulture);  
DateTime from=DateTime.ParseExact(date_from.Text, strDateFormat, CultureInfo.InvariantCulture); 

cmd.Parameters.AddWithValue("@to", to); 
cmd.Parameters.AddWithValue("@from", from); 
相關問題