1

I'm trying to retrieve data from database and display it in a listbox. I've got the following code and when I run it, it gives no error or something but no data is showing up in the listbox.

connection.Open();

DataTable dt = new DataTable();

OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Appointments where PersonID = '" + textBox4.Text + "'";

OleDbDataReader reader = command.ExecuteReader();

dt.Load(reader);

foreach (DataRow Dr in dt.Rows)
{
    listBox1.Items.Add(Dr["PersonID"].ToString());
}

connection.Close();
8
  • I believe you need to call listBox1.Refresh() - don't quote me on that though, I can't remember if that's it or not Commented Jan 17, 2016 at 16:36
  • I've added your suggestion but unfortunately it doesn't work. Commented Jan 17, 2016 at 16:38
  • 1
    Does the datatable contain any rows? Your SQL may not be getting any data from the database that meets the criteria. Commented Jan 17, 2016 at 16:39
  • 2
    Dont concat SQL, use Parameters; you are forcing an Id (int?) to text. There is no need to use a Datatable, you could just use the reader. If there are no matching rows nothing would happem. A breakpoint would reveal this Commented Jan 17, 2016 at 16:39
  • 1
    Print out dt.Rows.Length into the console to see if there are actuallly any rows Commented Jan 17, 2016 at 16:41

1 Answer 1

2

You don't show your connection string, but it sounds like one of the old gotchas when working with file based databases (Access as it seems you're using) from within Visual Studio.

If your MDB file is part of the project, and its "Action" is set to "Copy always", then every time you run your application, the MDB file in the BIN folder will get overwritten by the one in your source folder, thus overwriting any changes you made in the last run.

Please verify that this is not the case as it's one common source of problem.

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't matter. Because I'm adding the data when the application is running. So it's no problem that the data could get overwritten when launching the application.

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.