Click here to Skip to main content
15,916,601 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable(); SqlDataAdapter sda = new SqlDataAdapter("Select * from patient where Date between '" + dateTimePicker1.Text + "' and '" + dateTimePicker2.Text + "'", myconnection);
sda.Fill(dt);
dataGridView1.DataSource = dt;

        }


can anyone help whats the problem when i am clicking to see from one date to another date records

thanks in advance
Posted
Updated 19-Sep-15 21:30pm
v2

The main problem is that you concatenate the values directly to the SQL statement. This leaves you wide open to SQL injections and also causes problems since you're relying on implicit conversion from character data to datetime.

The cure is to use parameters. In other words your code should look something like
C#
DataTable dt = new DataTable(); 
SqlCommand sc = new SqlCommand();
sc.CommandText = "Select * from patient where Date between @date1 and @date2";
sc.Connection = myconnection;
sc.Parameters.AddWithValue("@date1", dateTimePicker1.Value);
sc.Parameters.AddWithValue("@date2", dateTimePicker2.Value);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = sc;
sda.Fill(dt);
dataGridView1.DataSource = dt;

(Sorry for possible typos)

Also you should use using blocks to ensure proper disposal of commands, connections and so on.

I'd also recommend reading Properly executing database operations[^]
 
Share this answer
 
For starters, stop doing it like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
C#
private void button1_Click(object sender, EventArgs e)
        {
        DataTable dt = new DataTable(); 
        SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM patient WHERE [Date] BETWEEN @ST AND @EN", myconnection);
        sda.SelectCommand.Parameters.AddWithValue("@ST", dateTimePicker1.Value);
        sda.SelectCommand.Parameters.AddWithValue("@EN", dateTimePicker2.Value);
        sda.Fill(dt);
        dataGridView1.DataSource = dt;
        }
The chances are that will solve your problem at the same time.

[edit]Typo: wrote "@ED" for "@EN" in the second parameter line.[/edit]
 
Share this answer
 
v2
Comments
Muhammad Qasim Ludin 20-Sep-15 7:10am    
Must declare the scalar variable "@EN".
OriginalGriff 20-Sep-15 7:15am    
Typo: Change "@ED" to "@EN" in the second parameter line.
Muhammad Qasim Ludin 20-Sep-15 7:20am    
thanks brother so much
OriginalGriff 20-Sep-15 7:32am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900