Reputation: 47
Using Visual studio coding C# I have a windows form and have two datetime pickers, how would I select two different date ranges and retrieve data from my SQL database. This is what I have done so far...
SqlConnection ssl = new SqlConnection();
ssl.ConnectionString = @"connection goes ";
ssl.Open();
var a = dateTimePicker1.Value.ToString("yyyy-MM-dd");
var b = dateTimePicker2.Value.ToString("yyyy-MM-dd");
SqlDataAdapter ad = new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >='" + a + "' AND modified_time <= '"+ b +"'", ssl);
DataTable dt = new DataTable();
ad.Fill(dt);
dataGridView1.DataSource = dt;
Upvotes: 0
Views: 9656
Reputation: 66449
When you do this:
"... >= '" + a + "' AND ..."
You're creating a string literal that has your date value in it. The database won't treat it as a date though, and if the query executes it won't do what you want.
Instead, parameterize your query, which is the correct way to pass the dates (or any other values) in:
SqlDataAdapter ad =
new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >= @Date1 AND modified_time <= @Date2", ssl);
ad.SelectCommand.Parameters.AddWithValue("@Date1", dateTimePicker1.Value);
ad.SelectCommand.Parameters.AddWithValue("@Date2", dateTimePicker2.Value);
Upvotes: 2