Mike
Mike

Reputation: 1610

Cant connect to remote MS Access database

I keep getting a

InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.]

It is because my connection is closed. What is wrong with my connection string? Why won't it open.

    protected void Page_Load(object sender, EventArgs e)
    {
        // Declaration section

        //OleDbConnection objDBConn;
        OleDbCommand    objCmd;
        OleDbDataReader objDR;

        //create connection object
        System.Data.OleDb.OleDbConnection conn = new
          System.Data.OleDb.OleDbConnection();

        // Modify the connection string and include any
        // additional required properties for your database.
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            @"Data source= c:\inetpub\wwwroot\cm485a2\rreAccesscm485a2.mdb";

          // Create OleDbCommand object with SQL to execute
            objCmd = new OleDbCommand("SELECT * " +
                            "  FROM customers " +
                            " ORDER BY cust_id", conn);

            // Create a DataReader and execute the command
            objDR = objCmd.ExecuteReader();

            // Copy results from DataReader to DataGrid object
            GridView1.DataSource = objDR;
            GridView1.DataBind();


            //close all objects
            conn.Close();
            conn.Dispose();

    }

Upvotes: 2

Views: 1634

Answers (3)

Nalin
Nalin

Reputation: 1

change your connection string as follows...

conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            @"Data source= c:\\inetpub\\wwwroot\\cm485a2\\rreAccesscm485a2.mdb";

*note: '\\' instead of '\'

Upvotes: -1

Marcote
Marcote

Reputation: 3105

You need to Open the connection first.

http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.open.aspx

also, I would use using to be avoid resource leaks, something like this:

using (var connection = new OleDbConnection())
{
  connection.Open();
  using (var command = new OleDbCommand("connectionString"))
  {
     //Do my stuff.
  }
}

This ways is easier to leave resources uncollected by the GC.

HTH

Upvotes: 6

TyCobb
TyCobb

Reputation: 9089

You need to call conn.Open() after you set your connection string.

Edit: Woops, Markust beat me to it by 40 seconds, xD

Upvotes: 2

Related Questions