2014-01-21 82 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); 
相关问题