- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming
C# program that interfaces with MS Access: Open an existing Access database file
1. Open a new Visual C# .NET windows application. Name the project OpentDatabase.
2.
Design a form. Add a Textbox and a Button
3. Set Name property of Textbox to “txtdatabaseName”.
4. Set Name property of Button to “btnOpen” and text property to “Open Database”.
5. In the code file add namespace: using System.Data.OleDb;
6. Double click on the Button and pest the following code into the “btnOpen_Click” event
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtDatabasePath.Text ;
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn); // create a connection object
myAccessConn.Open(); // open the connection
MessageBox.Show("Database connection is successfully Opened");
}
catch (Exception ex)
{
MessageBox.Show("Error: Failed to create a database connection. \n{0}", ex.Message);
}
if (myAccessConn.State == ConnectionState.Open) //check the connections status.
{
myAccessConn.Close(); // close the connection
MessageBox.Show("Database is successfully Closed");
}
7. Press F5 to build and run the project.
8. Put your existing database name with location like c:\MyAccessDB.mdb in the text box and then press the “Open Database” Button. Your access database connection will be opened.