Ashish Khadye

Ashish Khadye

  • NA
  • 62
  • 5.2k

How to get records between two dates c# ms-sql

Aug 4 2018 2:13 AM
Hello,
 
I have developed one windows application, and I want to search records between two dates selected by user.
 
Please tell me exact query to select records between two dates
 
Datatype of Date in sql table is nvarchar(50)
 
My code is :
 
dataGridViewSearchResults.Visible = true;
labeltot.Visible = true;
string startdate;
string enddate;
startdate = dateTimePickerstartdate.Value.ToString("dd/MM/yyyy");
enddate = dateTimePickerenddate.Value.ToString("dd/MM/yyyy");
double i = 0;
con.Close();
SqlCommand cmd = new SqlCommand("select * from Expenses where Date>='" + startdate.ToString() + "' and Date<='" + enddate.ToString() + "'", con);
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridViewSearchResults.DataSource = dt;
foreach (DataRow dr in dt.Rows)
{
i = i + Convert.ToDouble(dr["Amount"].ToString());
}
lbltotal.Text = i.ToString();
i have also tried this query -
select * from Expenses where Date BETWEEN '" + startdate.ToString() + "' AND '" + enddate.ToString() + "'
But its not giving proper result.
e.g. If we gave fromdate as - 01/07/2018 and todate as 31/07/2018 then in the results it gives records of 01/08/2018 also...
 
How to get desired result?

Answers (5)