Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The statement has been terminated.



my c# code.
string str = "insert into TblStock1 values('" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Value.ToString("dd/MM/yyyy") + "','" + textBox3.Text + "','" + comboBox1.Text + "')";


What I have tried:

my c# code.
<pre>string str = "insert into TblStock1 values('" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Value.ToString("dd/MM/yyyy") + "','" + textBox3.Text + "','" + comboBox1.Text + "')";
Posted
Updated 17-Apr-20 13:45pm

1 solution

Your C# code is a candidate for SQL Injection. You should NEVER EVER put together an SQL Command by concatenating command text with user input.

What you should be doing is using parameters for this, which will give you something like this
C#
string qry = "INSERT INTO TblStock1 VALUES (@txt1, @txt2, @dt1, @tx3, @cb1)";

SqlCommand = new SqlCommand(qry, connectionstring);
    cmd.Parameters.AddWithValue("@txt1", textBox1.Text);
    cmd.Paramaters.AddWithValue("@txt2", textBox2.Text);
//  cmd.Paramaters.AddWithValue("@dt1",  ** later **);
    cmd.Paramaters.AddWithValue("@txt3", textBox3.Text);
    cmd.Paramaters.AddWithValue("@cb1", comboBox1.Text);
Now onto your problem with the conversion...

Leave DateTime values as DateTime; they are numerical in nature and the only time formatting comes into play is when you are showing it to an end-user.
So the commented out line above should just be replaced with
C#
cmd.Paramaters.AddWithValue("@dt1", dateTimePicker1.Value );
 
Share this answer
 
v2
Comments
Member 11297177 18-Apr-20 10:28am    
Thanks for you quick reply , let me try and get back to you
Member 11297177 18-Apr-20 10:50am    
thanks for your help , your given solution worked fine .
MadMyche 18-Apr-20 11:01am    
Glad it all worked out.
Both of these are very common problems, so don't take it personally; just remember it for future development.
How common is this? I just gave this same basic answer to a new question but could not give them replacement code as I don't no Python.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900