C# 在sql数据库中插入短日期
将参数掩码文本框值(shortDate)插入sql server 2008时出现错误“无法将字符串识别为日期”我的代码:C# 在sql数据库中插入短日期,c#,sql-server-2008-r2,C#,Sql Server 2008 R2,将参数掩码文本框值(shortDate)插入sql server 2008时出现错误“无法将字符串识别为日期”我的代码: cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value = Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString(); 不要使用ToSortDateString,因为您要设置SqlDbType.Date您可以直接设置DateTime值,如下所示 c
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString();
不要使用
ToSortDateString
,因为您要设置SqlDbType.Date
您可以直接设置DateTime
值,如下所示
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text);
如果您有输入datetimem的格式,最好使用DateTime.TryParseExact
DateTime result;
if (DateTime.TryParseExact(
recievedDateTxt.Text, // The string you want to parse
"dd/MM/yyyy", // The format of the string you want to parse.
CultureInfo.InvariantCulture, // The culture that was used
// to create the date/time notation
DateTimeStyles.None, // Extra flags that control what assumptions
// the parser can make, and where whitespace
// may occur that is ignored.
out result)) // Where the parsed result is stored.
{
// your other codes
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value = result;
}
您可以使用
TryParseExact()
方法
试试这个:如果您的日期格式是:dd/MM/yyyy
DateTime result;
DateTime.TryParseExact(recievedDateTxt.Text,"dd/MM/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out result)
{
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =result;
}
你试过用这种方法吗。我正在使用这种方法 try { using (SqlConnection con = new SqlConnection(ConnectionSetting.SQLDBConnectionString())) { con.Open(); using (SqlCommand com = new SqlCommand("spName", con)) { com.CommandType = CommandType.StoredProcedure; com.Parameters.Add(new SqlParameter("@dilivery_date", Convert.ToDateTime(recievedDateTxt.Text))); using (SqlDataAdapter da = new SqlDataAdapter()) { da.SelectCommand = com; da.Fill(dtResult); } } } return dtResult; } catch (Exception) { throw; } 尝试 { 使用(SqlConnection con=newsqlconnection(connectionset.SQLDBConnectionString())) { con.Open(); 使用(SqlCommand com=newsqlcommand(“spName”,con)) { com.CommandType=CommandType.StoredProcess; Add(新的SqlParameter(“@dilivery_date”,Convert.ToDateTime(receiveddatext.Text)); 使用(SqlDataAdapter da=newsqldataadapter()) { da.SelectCommand=com; da.填充(dtResult); } } } 返回结果; } 捕获(例外) { 投掷; }
我试过这个。。但同样的错误…掩码文本框的方向是从右到左,然后,
Convert.ToDateTime(receivedDateText.text)
可能会失败,您输入的值是多少?我插入了2013年12月18日这只是另一种方法。这就是我在向存储过程传递值时使用的方法。我之所以发布它,是因为我认为它可能对某些人有所帮助。