Click here to Skip to main content
16,013,747 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
SqlConnection con = new SqlConnection("Data Source=server;Initial Catalog=f_library;User ID=sa;Password=ahmed");
con.Open();
SqlDataAdapter dad = new SqlDataAdapter("Select * from esrdat where esrdat_date between '" + Convert.ToDateTime(dateTimePicker1.Value) + "' and '" + Convert.ToDateTime(dateTimePicker2.Value) + "'", con); 
DataSet ds = new DataSet();
dad.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
    esrdatDataGridView.DataSource = ds.Tables[0];
}

con.Close();


I get this error
System.Data.SqlClient.SqlException was unhandled
Message="Syntax error converting datetime from character string."
Posted
Updated 31-Jan-12 0:17am
v2
Comments
lukeer 31-Jan-12 6:18am    
Please wrap code samples in <pre lang="c#">tags like these</pre>
This time, I did it for you.

Don't do that!
C#
SqlDataAdapter dad = new SqlDataAdapter("Select * from esrdat where esrdat_date between '" + Convert.ToDateTime(dateTimePicker1.Value) + "' and '" + Convert.ToDateTime(dateTimePicker2.Value) + "'", con); 

All it does is take a valid DateTime, use a default conversion to a string, then try to convert it back to a DateTime. Then pass that (as a number, converted back to a string via another default conversion) to SQL. But in your local format, rather than anythign SQL is expecting, which is ISO format.

Try:
C#
SqlDataAdapter dad = new SqlDataAdapter("Select * from esrdat where esrdat_date between @START AND @END", con);
dad.SelectCommand.Parameters.AddWithValue("@START", dateTimePicker1.Value);
dad.SelectCommand.Parameters.AddWithValue("@END", dateTimePicker2.Value);
 
Share this answer
 
v2
Comments
iceprincess50 31-Jan-12 6:46am    
thannnnnnnnnnnnnnnnnnnnnnnnnnnnnnx
walterhevedeich 1-Feb-12 2:22am    
Did a minor correction on the name of the second parameter.
Try using DateTime.TryParse method[^] to ensure you are converting an appropriate string to DateTime value.
 
Share this answer
 
Comments
lukeer 1-Feb-12 2:24am    
There is nothing to parse here. DateTimePicker.Value is already a valid DateTime.

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