I have a query that gets data from my database and it needs to filter out data between certain dates that the user will fill in two textboxes. I need to fill in the textboxes like: 2016-9-13 otherwise it wont work (the date in the database is also 2016-9-13). But when it fills the gridview the cell says: 13-9-2016.
I want to fill in the dates in the order like: 13-9-2016. How can i do this and what do i need to change?
Here is some code that gives me the data from the database.
connect = new SqlConnection(@"Data Source=LP12;Initial Catalog=Data;Integrated Security=True");
connect.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connect;
cmd.CommandText = "SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik, Toerental, DateTime, Schip FROM SysteemSensorInfo WHERE DateTime BETWEEN @StartDate AND @EndDate";
cmd.Parameters.AddWithValue("@StartDate", TextBoxBeginDatum.Text);
cmd.Parameters.AddWithValue("@EndDate", TextBoxEindDatum.Text);
DataSet ds = new DataSet();
new SqlDataAdapter(cmd).Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Basically, parse the dates and pass down DateTime
values:
cmd.Parameters.AddWithValue("@StartDate", ParseDate(TextBoxBeginDatum.Text));
cmd.Parameters.AddWithValue("@EndDate", ParseDate(TextBoxEindDatum.Text));
...
static DateTime ParseDate(string text) {
// TODO; possibly just: return DateTime.Parse(text);
}
You should use Datediff() function. Internally, It will manage valid date in any format for dates comparison.
"SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik, Toerental, DateTime, Schip
FROM SysteemSensorInfo
WHERE datediff(day,DateTime,@StartDate)<=0 AND datediff(day,DateTime,@EndDate)>=0"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.