VB.NET -> C# Syntax problems

979 views Asked by At

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.


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);
1

There are 1 answers

2
Joel Coehoorn On

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.