-1

I has a datagridview which contains information about some students, and i want to filter the data for showing only students have birthdate greater than datetimePicker1 and smaller than datetimePicker2 which were created in my form before. This is my code apply SqlDataAdapter but it not works at all:

SqlDataAdapter adap = new SqlDataAdapter("select * from Student where bdate >= '" + dateTimePicker1.Value + "' and bdate <= '" + dateTimePicker2.Value + "' ", mydb.getConnection);
DataTable table = new DataTable();
adap.Fill(table);
dataGridViewStudentList.DataSource = table;

*bdate is a column in my database that contains birthdate of students with type of Datetime. Anyone can help, thanks alot.

Giangtiny
  • 1
  • 1
  • 1
    You forgot to mention what is the Data Type of the `bdate` Column. You're treating it as a string. Is it? In that case, change to Date. – Jimi Mar 24 '21 at 15:11
  • 1
    **Always use parameterized sql and avoid string concatenation** to add values to sql statements. This mitigates SQL Injection vulnerabilities and ensures values are passed to the statement correctly. See [How can I add user-supplied input to an SQL statement?](https://stackoverflow.com/q/35163361/1260204), and [Exploits of a Mom](https://xkcd.com/327/). Using `DateTime` might not pose an injection threat but it could still cause problems due to how the instance is converted to a string during concatenation. – Igor Mar 24 '21 at 15:33
  • The type of bdate is Datetime and it not work, even i use cast function in sql to cast datetimepicker1.value to Datetime it still not work – Giangtiny Mar 25 '21 at 07:15
  • `DateTimePicker1.Value` (as the name of the Control implies) is already of Type DateTime. You need to use Command Parameters to pass values to the query (using `[Command].Parameters.Add()`, not `[Command].Parameters.AddWithValue()`). – Jimi Mar 25 '21 at 16:33
  • Thanks alot @Jimi it works – Giangtiny Mar 25 '21 at 17:42
  • Sure, no problem :) It's really important that you **never** use string concatenation to build your queries. Only use Command Parameters and only the `Parameters.Add()` / `.AddRange()` methods. `Parameters.AddWithValue()` can be used, relatively safely, with Stored Procedures only. – Jimi Mar 25 '21 at 17:45

1 Answers1

0

I think i know what is your problem. You need a sqlcommand or sqlselect and you have to add a parameter of type datetime and then u have to assign your datetimepicker value.

Getting values between from and to date from datetimepicker