Question

I am getting error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value." while executing the sqlcommand. The input of date time is "10/24/2013 06:25:30 PM" //C# Code

    string sa1 = dateTimePicker1.Value.ToString("MM/dd/yyyy");
    string fr = textBox1.Text;
    string dt = sa1 + " " + fr;
    string to = textBox2.Text;
    string dt1 = sa1 + " " + to;

    DateTime tim = DateTime.ParseExact(dt.ToString(), "MM/dd/yyyy hh:mm:ss tt",System.Globalization.CultureInfo.InvariantCulture);
    DateTime tim1 = DateTime.ParseExact(dt1.ToString(), "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
    DateTime tim2 = Convert.ToDateTime(tim);
    DateTime tim3 = Convert.ToDateTime(tim1);
    dataGridView1.Rows.Clear();
    SqlConnection con = new SqlConnection("Data Source=173.83.250.71,1433; Network Library=DBMSSOCN; Initial Catalog=paradigm;User Id=sa; password=Paradigm123");
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into paradigm.dbo.driverotcalc ( emp_no, fro, too, purpose, totalhrs, entdate, amount) values('" + emp.ToString() + "','" + tim2.ToString() + "','" + tim3.ToString() + "','" + textBox3.Text + "','" + textBox4.Text + "','" + DateTime.Now + "','" + textBox5.Text + "')",con);

    cmd.ExecuteNonQuery();

Can any one help me in resolving this issue.

Was it helpful?

Solution

You insert DateTime.Now. I suspect the format is not the same as the date format in your database. Try :

string formatDB ="YYYY/MM/dd";
DateTime.Now.ToString(formatDB);

Replace formatDB by your date format in your database

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top