blog

Home / DeveloperSection / Blogs / Listing the Databases connected to the DataSource

Listing the Databases connected to the DataSource

Shankar M 3236 19-Feb-2013

In this blog, I have discussed how to list all the Databases in SQL Server connected to a Data Source in C# Windows Forms.

Namespaces to be included to connect to SQL Server Database:

using System.Data;

using System.Data.SqlClient;

Add a ListView control to the Form.

Copy the code snippet to the Windows Form Load event:

     //Substitute your connection string below in ConnectionString 
        String ConnectionString =
           "Data Source=L04WEBMET001\\MSSQL2005;User id = LG_MssDev; password=LG@Dev765;";
        //The Using Keyword frees all the resources managed by the Connection automatically
        using(SqlConnection Sqlconn = new SqlConnection(ConnectionString))
        {
            Sqlconn.Open();
            //Get Schema Method returns the Schema Information for the DataSource that is Specified
            DataTable dtDbs = Sqlconn.GetSchema("Databases");
            Sqlconn.Close();
            //Columns.Add Method adds a column to the listView1 control
            listView1.Columns.Add("Databases");
            //Setting the listView1 View property to the Enumeration Details
            listView1.View= View.Details;
            //Fixing the Column Width property to 70
            listView1.Columns[0].Width = 70;
            //Setting the listView1 GridLines property to true to show Grid appear between rows and Columns
            listView1.GridLines = true;
 
            foreach(DataRow row in dtDbs.Rows)
            {
                //Use Items.Add Method of listView1 to add string to the collection 
                listView1.Items.Add(row["database_name"].ToString());
            }
        }

Thanks for reading.


c# c# 
Updated 18-Sep-2014

Leave Comment

Comments

Liked By