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))
            //Get Schema Method returns the Schema Information for the DataSource that is Specified
            DataTable dtDbs = Sqlconn.GetSchema("Databases");
            //Columns.Add Method adds a column to the listView1 control
            //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 

Thanks for reading.

  Modified On Sep-18-2014 01:24:09 PM

Leave Comment