Search code examples
c#.netwinformsms-accessoledb

OLEDB Parameterized Query


public void LoadDB()
{
    string FileName = @"c:\asdf.accdb";
    string query = "SELECT ID, Field1 FROM Table1 WHERE ID=? AND Field1=?";
    string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName;

    OleDbConnection odc = new OleDbConnection(strConn);
    dAdapter = new OleDbDataAdapter();
    OleDbCommand cmd = new OleDbCommand(query,odc);

    cmd.Parameters.Add("?", OleDbType.Integer, 5).Value = 1234;
    cmd.Parameters.Add("?", OleDbType.BSTR, 5).Value ="asdf";

    dAdapter.SelectCommand = cmd;

    ds = new DataSet();
    dAdapter.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
}

I'm trying to use parametrized query to bind the access file into the datagridview. It finds the column names fine, but the contents are empty.

How can I fix this issue?


Solution

  • In my test program, the ds.Tables[0].Rows.Count datatable actually had 1 row returned (as there was one row in my test database that matched the query itself). If you put a break on this line you should be able to see whether or not data is getting into the datatable in the first place. Try this:

    dataGridView1.DataSource = ds.Tables[0];
    

    What does the front end binding of dataGridView1 look like? Running the query in Access could shed some light on the situation too.