Question

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
        string strcon = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Fellipe\\documents\\visual studio 2010\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=True;User Instance=True";
        SqlConnection conexao = new SqlConnection(strcon);
        conexao.Open();
        SqlDataAdapter Buscar = new SqlDataAdapter("SELECT ROTA, DOCA FROM Planilha4 WHERE D2 =" + monthCalendar1.SelectionStart.ToString("dd/MM/yyyy"), conexao);
        DataTable dt = new DataTable();
        Buscar.Fill(dt);

       SqlDataAdapter sda = new SqlDataAdapter();
       BindingSource bSource = new BindingSource();

       bSource.DataSource = dt;
       dataGridView1.DataSource = bSource;
       sda.Update(dt);


    }

The error is thrown at Buscar.Fill(dt); I would like to eliminate this error. I'm waiting for the reply. Thanks

Était-ce utile?

La solution 2

You are missing some " ' ' " before and after your monthCalendar1.SelectionStart.ToString("dd/MM/yyyy"). See below:

SqlDataAdapter Buscar = new SqlDataAdapter("SELECT ROTA, DOCA FROM Planilha4 WHERE D2 = '" + monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "'", conexao);

Also, I would highly suggest that you parameterize your query if you have an external dependency on a control like monthCalendar1. Here is a simple example:

string command = "SELECT ROTA, DOCA FROM Planilha4 WHERE D2 = @mnthCalendar";
sqlDA.SelectCommand.Parameters.Add(@mnthCalendar, SqlDbType.DateTime).Value = monthCalendar1.SelectionStart;

Autres conseils

If you look at the resulting SQL string after you build it, you will see the problem. There are no quotation marks around the date literal so SQL is treating your date with slashes as a math equation.

You should look in to either using a stored procedure or a parameterized SQL string to prevent this problem. You can search for "sql injection vulnerabilities" on this site to see lots of examples of using parameters in SQL. Here's a related question.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top