SiteMap  | About    

How to find tables in a Database in C#

A database is a collection of information organized to provide efficient retrieval . A database is made up of many linked tables of rows and columns, each containing specific data. A table is a set of data elements that is organized using a model of vertical columns and horizontal rows.

In some situations you may want to know how many tables exist in your database. Everything about your SQL Server database is stored in its system tables. In these situations you can use the following SQL for finding how many tables in a database.

  Select DISTINCT(name) FROM sys.Tables

Returns a row for each table object, currently only with sys.objects.type = U.

using System;
using System.Collections.Generic;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)

            string connetionString = null;
            SqlConnection connection;
            SqlCommand command;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            int i = 0;
            string sql = null;

            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Select DISTINCT(name) FROM sys.Tables";

            connection = new SqlConnection(connetionString);

                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;

                for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            catch (Exception ex)
                MessageBox.Show("Can not open connection ! ");

} (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.