I must have missed something here. I am trying to create a table but I am getting an error telling me that connection is still open. But where??? I have re-read the code but I can't find where the connection is still open...
Problem lays here: objOleDbConnection.Open()
Error say:
You attempted to open a database that is already opened by user 'Admin' on machine 'machine'. Try again when the database is available.
private void sfdNewFile_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
// Creating a ADOX object needed to create
// new MS Access file.
ADOX.Catalog createMSFile = new ADOX.Catalog();
// Creating an object for a table.
Table nTable = new Table();
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False;Mode=12";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Created a new MS Access 2007 file with specified path.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
sfdNewFile.FileName);
objOleDbConnection.Open();
objOleDbCommand.CommandText = "CREATE TABLE PersonalData (" +
"[DataID] AUTOINCREMENT NOT NULL PRIMARY KEY ," +
"[Type] VARCHAR(40) NOT NULL ," +
"[URL] VARCHAR(40) NOT NULL ," +
"[SoftwareName] VARCHAR(40) NOT NULL ," +
"[SerialCode] VARCHAR(40) NOT NULL ," +
"[UserName] VARCHAR(40) NOT NULL ," +
"[Password] VARCHAR(40) NOT NULL";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// It is importnat to release COM object, in this very order
// otherwise we eill end up with an error.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(createMSFile);
// Closing the connection to the database.
objOleDbConnection.Close();
}
}
It seems that the ADOX object should close its connection as well. Look at the following sample from Microsoft: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681562(v=vs.85).aspx
Their ADOX object is named cat. They have the following:
cat.ActiveConnection = Nothing
Which will probably translate to:
createMSFile.ActiveConnection = null
In your code (probably in the first Finally block). I think it's the ADOX object that makes the difference, before dispoing it, try to set it's ActiveConnection to null.