fetch column names for specific table

krunal shah picture krunal shah · Sep 23, 2010 · Viewed 18.2k times · Source

I want to fetch all the column names for specific table..

I am using msaccess and C# .net 2008.

Answer

Nathan Baulch picture Nathan Baulch · Sep 23, 2010

You can fetch schema information for a given query through OleDb using the SchemaOnly CommandBehavior and the GetSchemaTable method, as follows:

var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";
using (var con = new OleDbConnection(conStr))
{
    con.Open();
    using (var cmd = new OleDbCommand("select * from Suppliers", con))
    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
    {
        var table = reader.GetSchemaTable();
        var nameCol = table.Columns["ColumnName"];
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine(row[nameCol]);
        }
    }
}