How to Get Column Name of a Particular Table from Database

This blog gives you information about how to get column name of a particular table from database.

Here .cs file : Program.cs

namespace ColumnNames

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                var objDataset1 = new DataSet();

                var presentTable = new DataSet();

                Console.Write("Enter Database Name : ");

                var dbname = Console.ReadLine();

                Console.WriteLine();

                Console.Write("Enter Table Name : ");

                var tname = Console.ReadLine();

                Console.WriteLine();

                #region Connection String For Database

                OleDbConnection conn = new OleDbConnection();

                conn.ConnectionString =

                "provider=SQLOLEDB;" +

                "Data Source=ServerName;" +

                "Initial Catalog=" + dbname + ";" +

                "User id=UserName;" +

                "Password=Secrete;";

                conn.Open();

 

                #endregion Connection String For Database

 

                #region Is Table Present

 

                // Check table present or not in database

                var isPresentTable = new OleDbCommand("Select * from INFORMATION_SCHEMA.TABLES where table_name='" + tname + "';", conn);

                var res = new OleDbDataAdapter(isPresentTable);

                res.Fill(presentTable);

                if (presentTable.Tables[0].Rows.Count == 0)

                {

                    Console.WriteLine("Table Not Present");

                    return;

                }

 

                #endregion

 

                OleDbCommand objCmdSelect = new OleDbCommand("select * from " + tname + ";", conn);

                var objAdapter1 = new OleDbDataAdapter(objCmdSelect);

                objAdapter1.Fill(objDataset1);

                Console.WriteLine("Column Names of Table ");

                Console.WriteLine();

                //Featch column name of a table from the dataset

                foreach (DataColumn column in objDataset1.Tables[0].Columns)

                {

                    Console.WriteLine(column.ColumnName);

                }

                conn.Close();

            }

            catch (Exception)

            {

                throw;

            }

            Console.ReadKey();

        }

    }

}

Output


Image.jpg