tags:

views:

289

answers:

2

I want to create a new MS Access database table using ADOX. On this page, is code in VB.NET, but obviously it's not working in C# (when I want to "convert" the code). I'll be grateful if someone converts it correctly.

A: 

In VB.NET is:

     Dim Cn As ADODB.Connection, Cat As ADOX.Catalog, _
                        objTable As ADOX.Table

but, in C#, there's no ADODB.Connection method

here's my code, I don't really think it's OK:

        string ConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/App_Data/TempDB.mdb") + ";";
        OleDbConnection conn = new OleDbConnection(ConnStr);

        ADOX.Catalog Cat = new ADOX.Catalog();
        ADOX.Table objTable = new ADOX.Table();
        conn.Open();

        Cat.ActiveConnection = conn; //Here is the error message "Specified cast is not valid."

        objTable.Name = "Table2";

        objTable.Columns.Append("ID", DataTypeEnum.adVarChar, 100);

        objTable.Keys.Append("PrimaryKey", KeyTypeEnum.adKeyPrimary, "ID", "Table1", "IDColumn");

        Cat.Tables.Append(objTable);
Tony
Don't use ADODB.Connection and it's kin in VB.Net unless you have to. Use System.Data.OleDb.OleDbConnection and other types in the System.Data.OleDb namespace or other System.Data providers instead.
Joel Coehoorn
And don't "reply" to your own question when using StackOverflow unless you've actually found an answer you want to share. _Edit_ your original question instead.
Joel Coehoorn
... your error message is because you've used an OleDBConnection instead of adding a reference to ADODB and using an ADODB.Connection.
MarkJ
+2  A: 

Don't forget to add a reference to the ADOX assembly in your project. Once you've done that, the C# code would look like this:

using System;
using ADOX;

namespace ConsoleProgram1
{
    public class ConsoleProgram1
    {

        public static void Main(string[] args)
        {

              Catalog cat = new Catalog();

              cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" & _
                 "Data Source=D:\AccessDB\NewMDB.mdb;" & _
                 "Jet OLEDB:Engine Type=5");

              Console.WriteLine("Database Created Successfully")

        }

    }
}

Although my exposure to ADOX is limited to this question, the code snippets I saw at your link aren't encouraging. Things like the cat = Nothing line demonstrates a misunderstanding of how .Net changed things when from VB6. Hopefully that doesn't extend to the library.

Joel Coehoorn
The `cat = Nothing` wasn't necessary in the original VB6 either.
MarkJ
+1 The suggestion to use cat.Create to avoid using an ADODB.Connection is inspired.
MarkJ