3

I am trying to execute an SQL command on an Access Database over an OleDbConnection using C# and use that information to fill a DataGridView on a windows form. I have opened the connection, stated the query, and executed it, but I cannot find how to output the results to the DataGridView on the windows form (named dataOutput).

    private void Query()
    {
        string cmdText = "SELECT * FROM RetentionTable " +
            "WHERE [DateTime] BETWEEN '" + getDateTimeFrom("") + "' AND '" + getDateTimeTo("") + "'";

        string ConnectionPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=RetentionDB.mdb";

        try
        {
            OleDbConnection cn = new OleDbConnection(ConnectionPath);
            DataSet objDataSet = new DataSet();
            OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();

            if (cn.State.Equals(ConnectionState.Closed))
            {
                cn.Open();
            }

            OleDbCommand OleDbSearch = new OleDbCommand(cmdText, cn);
            OleDbSearch.ExecuteNonQuery();

            objDataAdapter.Fill(objDataSet);
            dataOutput.DataSource = objDataSet;
            cn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
            MessageBox.Show(ex.StackTrace.ToString());
        }

    }

From what I can see, the query is being executed correctly, but the issue comes when trying to use the objDataAdapter.Fill. I guess I am not understanding how to fill the DataSet with the output from the query. Any help would be much appreciated. Thanks!

5 Answers 5

3

Replace with ExecuteDataSet method

..
OleDbSearch.ExecuteDataSet();
objDataAdapter.Fill(objDataSet);
dataOutput.DataSource = objDataSet;
...

I suggest you to set your close connection in using blok or try with Finally of your try catch

Best practise

 using( var cn = new OleDbConnection(ConnectionPath))
 {
    ... 
 }
Sign up to request clarification or add additional context in comments.

Comments

1

A few comments:

  1. Your query is subject to SQL injection. Use a parameterised query instead.
  2. You don't need to open/close the connection; the DataAdapter will do that for you.
  3. You should wrap the OleDbConnection and OleDbCommand objects in a using block to ensure that their resources are cleaned up.
  4. You don't need to call ExecuteNonQuery, or any other Execute... method on the command;
  5. You need to assign the command to the SelectCommand property of the OleDbDataAdapter, or pass it to the constructor.

Try something like this:

private void Query()
{
   const string ConnectionPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=RetentionDB.mdb";

   try
   {
      using (var cn = new OleDbConnection(ConnectionPath))
      using (var cmd = new OleDbCommand("SELECT * FROM RetentionTable WHERE [DateTime] BETWEEN ? And ?"))
      {
         // Parameter names don't matter; OleDb uses positional parameters.
         cmd.Parameters.AddWithValue("@p0", getDateTimeFrom(""));
         cmd.Parameters.AddWithValue("@p1", getDateTimeTo(""));

         var objDataSet = new DataSet();
         var objDataAdapter = new OleDbDataAdapter(cmd);
         objDataAdapter.Fill(objDataSet);

         dataOutput.DataSource = objDataSet;
      }
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message.ToString());
      MessageBox.Show(ex.StackTrace.ToString());
   }
}

1 Comment

SO I did this and it seems to be executing correctly, but there is no data being shown in the grid view. It just shows no entries. I have AutoGenerateColuns = true, but there is no data. Any ideas?
0

I think you can also load the data into a DataTable and point the DataGridView to the table:

DataTable dt = new DataTable();
dt.Fill(OleDbSearch.ExecuteReader());
dataOutput.DataSource = dt;

Comments

0

You should not execute OleDbSearch.ExecuteNonQuery this is used only for queries that modify data (INSERT/UPDATE). Instead assign you command to dataadatper:

objDataAdapter.SelectCommand = OleDbSearch;

And then do your Fill and DataSource assignment.

Comments

0

The correct way to retrieve a DataSet using an OleDbDataAdapter is to associate the OleDbCommand to the SelectCommand property of the OleDbDataAdapter. You simply pass the OleDbCommand to the constructor of the OleDbDataAdapter.

Also your code should use a parameterized query for the text of the command, not a string concatenation. Using parameterized query allows you to avoid Sql Injections and the correct parsing of your text, date, decimals variable is done by the framework code.

   string cmdText = "SELECT * FROM RetentionTable WHERE [DateTime] BETWEEN ? AND ?";
   string ConnectionPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=RetentionDB.mdb";
   try
   {
        using(OleDbConnection cn = new OleDbConnection(ConnectionPath))
        using(OleDbCommand OleDbSearch = new OleDbCommand(cmdText, cn))
        using(OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(OleDbSearch))
        {
            OleDbSearch.Parameters.AddWithValue("@p1", getDateTimeFrom(""));
            OleDbSearch.Parameters.AddWithValue("@p2", getDateTimeTo(""));
            DataSet objDataSet = new DataSet();
            cn.Open();
            objDataAdapter.Fill(objDataSet);
            dataOutput.DataSource = objDataSet;
        }
    }
    catch (Exception ex)
    {
         MessageBox.Show(ex.Message.ToString());
         MessageBox.Show(ex.StackTrace.ToString());
    }

The using statement is another point to take note. This will ensure a correct closing and disposing of the connection, command and adapter also in case of exceptions.

2 Comments

This is then giving me the error showing "The SelectCommand property has not been initialized before calling "Fill".
That's really strange. As you can see from the docs here msdn.microsoft.com/en-us/library/0wz82t73.aspx passing the OleDbCommand to the constructor of the OleDbDataAdapter assigns the SelectCommand property

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.