2013-12-20 157 views
0

插入参数掩码文本框的值(shortDate)到SQL Server 2008有错误“无法识别字符串作为日期”我的代码:插入短日期到SQL数据库

cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value = 
Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString(); 

回答

1

不使用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; 
} 
+0

我想这..但同样的错误......面具文本框中的方向是从右到左 – Hamonbatra

+0

然后,'Convert.ToDateTime(recievedDateTxt.Text)'可能会失败,有什么价值,你输入? – Damith

+0

我插入18/12/2013 – Hamonbatra

0

您可以使用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;    
} 
0

你有没有尝试使用这种方法。我正在使用这种方法。

 

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; 
      } 

+0

你的答案如何解决问题? – Damith

+0

这只是另一种方法。这是我将值传递给存储过程时使用的。我发布,因为我认为这可能有助于某人。 – Damith