Access query with DateTimePicker type dates in C #

1

Good morning. I have a problem with my code. Does not understand the variables for a query between dates DateTimePicker .

This is my code.

public DataTable selcfecharegitro()
    {
        DataTable dt = new DataTable();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        OleDbConnection cone = new OleDbConnection(cc.conaccess);
        DateTime desde = Convert.ToDateTime(new datosform().dtpdesde);
        DateTime hasta = Convert.ToDateTime(new datosform().dtphasta);
        da.SelectCommand = new OleDbCommand("select * FROM Registro where Fecha_uso between = '" + desde + "' and '" + hasta + "' ", cone);

        da.Fill(ds);

        dt = ds.Tables[0];

        return dt;
    }

and it shows me this error at the time I look for the range of dates.

  

Additional information: Unable to cast object of type 'System.Windows.Forms.DateTimePicker' to type 'System.IConvertible'.

    
asked by use2105 20.12.2016 в 13:43
source

1 answer

2

These problems always arise because you do not use Parameterized Queries , which solve this type of problems, as well as SQL injection .

On the other hand, to get the selected value in a DateTimePicker , you must access the property Value , which returns a DateTime .

Try this code:

...
DateTime desde = new datosform().dtpdesde.Value;
DateTime hasta = new datosform().dtphasta.Value;
da.SelectCommand = new OleDbCommand("select * FROM Registro where Fecha_uso between @desde and @hasta", cone);
da.SelectCommand.Parameters.AddWithValue("@desde",desde);
da.SelectCommand.Parameters.AddWithValue("@hasta",hasta);
da.Fill(ds);
    
answered by 20.12.2016 в 13:47