0
<asp:TextBox ID="txtBox" runat="server">
</asp:TextBox>
<asp:CalendarExtender ID="ce" runat="server" TargetControlID="txtBox" Format="dd-MMM-yyyy">
</asp:CalendarExtender>

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection239"].ToString()))
{
    SqlCommand cmd = new SqlCommand("insert into tbl_testing(dttm) values('"+DateTime.Parse(txtBox.Text)+"')", con);
    con.Open();
    cmd.ExecuteNonQuery();
}

when i execute following error is coming. In which format should I send the date to sql server

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated. Thanks in advance

1
  • Give us some examples of the dates that work and the dates that don't... Commented Dec 13, 2010 at 9:41

5 Answers 5

2

Use following code instead:

        SqlCommand cmd = new SqlCommand("insert into tbl_testing(dttm) values(@dttm)", con);
        cmd.Parameters.AddWithValue("@dttm", DateTime.Parse(txtBox.Text));
        con.Open();
        cmd.ExecuteNonQuery(); 
Sign up to request clarification or add additional context in comments.

Comments

2

Use parameters in your query, instead of string concatenation. Not only will your datetime problems be gone, but your query will also not be vulnerable to sql injection.

Next to that, you can also use a DateTimePicker instead of textbox, can't you ?

var command = conn.CreateCommand();
command.CommandText = "insert into tbl_testing(thecol) values(@p_someDate)";
command.Parameters.Add ("@p_someDate", SqlDbType.DateTime).Value = datetimePicker.Value;
command.ExecuteNonQuery();

1 Comment

query is executing sometimes. but when i take Dec 31-2010, it gives me error. kindly provide me solution.
1

Just pass the value via SqlParameter and NEVER use string concatenation.

Comments

0
mm-dd-yyyyThh:mm:ss

Comments

0

Make sure the server (local or otherwise) is using the correct time. For e.g if its British or American. Dates are also wrapped in ' '. It seems you are wrapping it in " "?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.