Reputation: 178
insert parameter mask text box value (shortDate) to sql server 2008 has error 'cannot recognize string as date' my code :
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text).ToShortDateString();
Upvotes: 0
Views: 1706
Reputation: 26209
You can use TryParseExact()
method
Try This: if your dateformat is : 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;
}
Upvotes: 0
Reputation: 2082
Did you try using this method. I am using this method.
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; }
Upvotes: 0
Reputation: 63065
don't use ToShortDateString
, since you going to set SqlDbType.Date
you can directly set DateTime
value as below
cmd.Parameters.Add("@dilivery_date", SqlDbType.Date).Value =
Convert.ToDateTime(recievedDateTxt.Text);
if you have format for input datetimem, you better use 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;
}
Upvotes: 1