C# 从字符串转换日期和/或时间时转换失败
将数据添加到数据库时,date_to和date_from中出现错误。 在sql server数据库中,date\u to和date\u from的数据类型为date。提出一些解决方案C# 从字符串转换日期和/或时间时转换失败,c#,sql-server-2008,C#,Sql Server 2008,将数据添加到数据库时,date_to和date_from中出现错误。 在sql server数据库中,date\u to和date\u from的数据类型为date。提出一些解决方案 try { cmd = new SqlCommand("insert into license1 values(@l_id,@customer_id,@d_id,@device_name,@from,@to)", cn); cmd.Parameters.AddWithValue("@l_id", li
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);
}
我认为你的日期格式可能导致了这个问题。必须使用SQL提供程序支持的日期格式。大多数SQL使用MM-dd-yyyy格式。所以,如果您通过了2014年1月21日,SQL server不会接受它,因为21个月不存在 将转换掌握在自己手中:
cmd.Parameters.AddWithValue("@to", DateTime.Parse( date_to.Text));
cmd.Parameters.AddWithValue("@from", DateTime.Parse( date_from.Text));
如果仍然失败,请使用具有适当格式和文化信息的DateTime.ParseExact()
版本
<>你可能想考虑添加一个更健壮和广泛的验证层。日期和数字对输入错误、用户设置和用户假设非常敏感
始终假定TextBox。文本中充满了错误 试试这个
cmd.Parameters.AddWithValue("@to",Convert.ToDateTime(date_to.Text));
cmd.Parameters.AddWithValue("@from",Convert.ToDateTime( date_from.Text});
如果用户输入的日期格式为: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);
如果在执行代码时问题仍然存在,可能是由于两个重要原因:
您已经使用了DateTime.Now.toSortString
或类似的自动转换方法,并且
您在设置中更改了计算机的默认日期时间格式
更改计算机的日期时间格式或将自动转换更改为“parse”方法。始终发布准确的错误消息。用户在文本框中输入的日期格式是什么?SQL Server中唯一真正的区域性不变日期时间格式是YYMMDD。