1

When I run this code, I get table columns without data.

Date is designed as Short text in Ms Access database.

connection.Open();
OleDbCommand cmd = new OleDbCommand();
try
{
    String date = dateTimePicker1.Value.ToString();

    cmd.Connection = connection;
    String query = "SELECT * from Events where DOB ='"+date+"'";

    cmd.CommandText = query;
    Console.WriteLine("" + query);
  
    OleDbDataAdapter oa = new OleDbDataAdapter(cmd);
    DataTable dt = new DataTable();
    oa.Fill(dt);
    dataGridView1.DataSource = dt;
}

How to solve that?

8
  • Does this answer your question? C# Data Connections Best Practice? Commented Jan 24, 2021 at 15:03
  • What are good ways to prevent SQL injection? Commented Jan 24, 2021 at 15:10
  • Can you check in your debugger what is value String date =dateTimePicker1.Value.ToString(); Commented Jan 24, 2021 at 15:10
  • What is the format of the value date passed to the query? Commented Jan 24, 2021 at 15:11
  • Does this answer your question? Turning a SqlCommand with parameters into a DataTable Commented Jan 24, 2021 at 15:12

1 Answer 1

0

Force a format on the date value:

DateTime date = dateTimePicker1.Value;

String query = "SELECT * from Events where DOB = #" + date.ToString("yyyy'/'MM'/'dd") + "#";
Sign up to request clarification or add additional context in comments.

5 Comments

@OlivierRogier: Nothing to "inject" here; a DatePicker can only return a date value.
@.Gustav Even if you are sure that the ToString formatting parameter as well as the query cannot be badly written to be SQL infected, and that no other coder can modify this line of code, or that the type in the database will never be changed, this is a very bad habit of not getting into the good habit of using SQL parameters, I think, because it quickly becomes a bad habit, and it will be hard to undo that.
@OlivierRogier: Of course, parameter usage is optimum, but if you can't write a correct hard-coded format string, you are facing major challenges.
Thanks @Gustav that was very helpful. I'm able to have data on all columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.