插入参数掩码文本框的值(shortDate)到SQL Server 2008有错误“无法识别字符串作为日期”我的代码:插入短日期到SQL数据库
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString();
插入参数掩码文本框的值(shortDate)到SQL Server 2008有错误“无法识别字符串作为日期”我的代码:插入短日期到SQL数据库
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString();
不使用ToShortDateString
,因为你去设置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; }
我想这..但同样的错误......面具文本框中的方向是从右到左 – Hamonbatra
然后,'Convert.ToDateTime(recievedDateTxt.Text)'可能会失败,有什么价值,你输入? – Damith
我插入18/12/2013 – Hamonbatra