anfd
anfd

Reputation: 119

How to get all table names and also column name using C# in MS Access?

How to get the name of all the tables and the name of the column table in Access 2007 with C#?

I want to bind the name of the table to a combobox and the column name to a listbox.

Upvotes: 3

Views: 3702

Answers (2)

anfd
anfd

Reputation: 119

this code is :

 OpenFileDialog openfiledialog1 = new OpenFileDialog();
        openfiledialog1.Title = "path select ";

        openfiledialog1.Filter = "Access 2003 (*.mdb)|*.mdb|Access 2007|*.accdb";
        if (openfiledialog1.ShowDialog() == DialogResult.OK)
        {
            txtpath.Text = openfiledialog1.InitialDirectory + openfiledialog1.FileName;
            using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openfiledialog1.FileName))
            {

                con.Open();
                DataTable schema = con.GetSchema("Columns");
                foreach (DataRow row in schema.Rows)
                {         
                   listBox1.Items.Add(row.Field<string>("COLUMN_NAME"));
                   cmbloadtable.Items.Add(row.Field<string>("TABLE_NAME"));
                }

            }
        }

Upvotes: 0

Steve
Steve

Reputation: 216293

This simple method will give you back a datatable that contains the name of all your columns

void Main()
{
     using(OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + 
            @"Data Source=D:\temp\temp.mdb;Persist Security Info=False;")) 
     { 
       con.Open();
       DataTable schema = con.GetSchema("Columns");
       foreach(DataRow row in schema.Rows)
           Console.WriteLine("TABLE:" + row.Field<string>("TABLE_NAME") + 
                             " COLUMN:" + row.Field<string>("COLUMN_NAME"));
    }
}

You could also try to change "Columns" with "Tables" to obtain a different datatable with more info on your tables. (Also "Indexes" for indexes)

Upvotes: 5

Related Questions