Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Dear All,
I am writing C# with MS Access database.When I write select query with criteria as date.
Access database that isn't know date format when I select date over current year 2013.Example today is 28/09/2013,I enter date 14/09/2013 or 15/09/2013 or 25/09/2013 over 13.In the database,It know the date like that 13/09/2014 or 13/09/2015 or 13/09/2025.So how can I try to get exactly date as my parameter.Here is my writing code.

C#
string vFDate, vTDate, vStr;
vFDate = Convert.ToDateTime(txtFDate.Text).ToShortDateString();
vTDate = Convert.ToDateTime(txtTDate.Text).ToShortDateString();

//vFDate = 01/09/2013 or 12/09/2013 and vTDate = 28/09/2013 is ok,it's working.
//But
//vFDate = 18/09/2013 and vTDate = 28/09/2013 is not ok.So Date is changed.Like that
//vFDate = 13/09/2018 and vTDate = 13/09/2028

vStr = "Selec * From tbl Where R_Date Between  Format(#" + vFDate + "#, 'dd/mm/yyyy') And   Format(#" + vTDate + "#, 'dd/mm/yyyy')";
OleDbCommand cmd = new OleDbCommand(vStr, OleDBComm);
OleDBConn.Open();
cmd.ExecuteNonQuery();
OleDBConn.Close();
Posted
Updated 27-Sep-13 23:59pm
v3

Don't do it like that! Why are you taking a string, converting it to a DateTime, then back to a string again, to add to another string, to pass to SQL where it has to be converted back to a DateTime to compare it? Use parametrized queries instead (You should be anyway to avoid SQL injection attacks)
C#
string vFDate, vTDate, vStr;
DateTime vFDate = Convert.ToDateTime(txtFDate.Text);
DateTime vTDate = Convert.ToDateTime(txtTDate.Text);
vStr = "SELECT * FROM tbl WHERE R_Date BETWEEN @FD AND @TD";
OleDbCommand cmd = new OleDbCommand(vStr, OleDBComm);
cmd.Parameters.AddWithValue ("@FD", vFDate); 
cmd.Parameters.AddWithValue ("@TD", vTDate);
OleDBConn.Open();
cmd.ExecuteNonQuery();
Chances are, you problem will disappear at the same time!

But if you must use a text box for date entry (and I'd use a DateTimePicker instead), then you should use DateTime.TryParse instead of Convert.ToDateTime.
 
Share this answer
 
Thanks you for your help. But I can Solve myself. By using like that following.
C#
string vFDate, vTDate;

vFDate = txtFDate.Value.ToString("yyyy/MM/dd");
vTDate = txtTDate.Value.ToString("yyyy/MM/dd");


And my select query like that
SQL
Select * From tbl where date between #" + vFDate + "# And #" + vTDate + "#"


Thanks everyone.


[Edit member="Tadit"]
Corrected formatting issues.
[/Edit]
 
Share this answer
 
v2
Comments
Member 12068191 6-May-16 7:37am    
HI BRO SAME PROBLEM HERE ... I'M RECORD DATA IN DB WITH DD/MM/YYYY FORMAT BUT RESULT NO ACCURATE....
Member 12068191 6-May-16 10:38am    
THANKS BRO IT WORK FINE :) THNKS

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