Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear friends,

I need to print below sql sum into c# windows form application. here is the code i was using for this. but i'm getting an error.

SQL Query as fallows. this one is working
SQL
SELECT SUM (COUNT)  FROM  Count_EPF WHERE date = '6/17/2015'>


conversion failed when converting datetime from character string

hear is my code

C#
string query = "SELECT SUM (COUNT)  FROM  Count_EPF WHERE date = '@C' ";

                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.AddWithValue("@C", dateTimePicker1.Text);

                    cmd.ExecuteNonQuery();
                    object result = cmd.ExecuteScalar();
                    txtView.Text = Convert.ToString(result);
Posted

1 solution

Remove the quotes:
SQL
string query = "SELECT SUM (COUNT)  FROM  Count_EPF WHERE date = '@C' ";
Becomes:
SQL
string query = "SELECT SUM (COUNT)  FROM  Count_EPF WHERE date = @C ";
Otherwise the parameter name is within an SQL string and is not treated as a parameter at all.

[edit]
Oh, and don't pass the string - pass the DateTime, value directly:
C#
cmd.Parameters.AddWithValue("@C", dateTimePicker1.Value);

That way, SQL doesn't have to interpret the string into a date with all the possible misinterpretations that can cause.
[/edit]
 
Share this answer
 
v2
Comments
Neranjana pathirana 16-Jun-15 5:38am    
Thanks Friend. it's working now
OriginalGriff 16-Jun-15 5:58am    
You're welcome!
Abhipal Singh 16-Jun-15 5:41am    
Elegant!
5ed..

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