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


C#
private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            cmd = new SqlCommand("INSERT INTO Login(Admin,Password,Age,Gender,Dateofbirth)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','"+textBox3.Text+"','"+ Gender +"','"+this.dateTimePicker1.Value.ToString("dd/mm/yyyy hh:mm") +"')", con);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("data Registered successfully!");
        }
Posted
Updated 7-Jul-14 2:26am
v2
Comments
Member 10918596 7-Jul-14 7:34am    
i got tis error The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. ..


wht can i do pls help me...
[no name] 7-Jul-14 7:41am    
Use a proper parameterized query and your problem might just go away all by itself.
Member 10918596 7-Jul-14 7:44am    
give example pls
[no name] 7-Jul-14 7:48am    
Why? You were given an example 4 days ago. Should I give you another example for you to ignore?
Bernhard Hiller 7-Jul-14 8:26am    
Repost:
http://www.codeproject.com/Questions/794023/The-conversion-of-a-varchar-data-type-to-a-datetim?arn=12

 
Share this answer
 
v2
hey, you shouldn't put a textbox.text inside your database query. That will open a huge cue to sql injection

cmd = new SqlCommand("INSERT INTO Login(Admin,Password,Age,Gender,Dateofbirth)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','"+textBox3.Text+"','"+ Gender +"','"+this.dateTimePicker1.Value.ToString("dd/mm/yyyy hh:mm") +"')", con);

use add parameters instead. just like that link Peter provided you

C#
cmd.CommandText = "INSERT INTO person (birthdate) VALUES(@date)";
            cmd.Parameters.Add(new SqlParameter("@date", dateTimePicker.Value.Date));
            //con is sql connection
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
 
Share this answer
 
C#
private void button1_Click(object sender, EventArgs e)
{
//do all  stuffs for creating command class's object
con.Open(); //con is the object of connection class

cmd.CommandText = "INSERT INTO person (birthdate) VALUES(@date)";
            cmd.Parameters.Add(new SqlParameter("@date", dateTimePicker.Value.Date));
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("data Registered successfully!");
}
 
Share this answer
 
change datetime format like "dd-MM-yyyy" to "MM-dd-yyyy" now u get o/p
 
Share this answer
 

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



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