How to get list of all database from sql server in a combobox using c#.net

First add following assemblies:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Management.Sdk.Sfc.dll
  • Microsoft.SqlServer.Smo.dll

from

C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\

and then use below code:

var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");

foreach (Database db in server.Databases) {
    cboDBs.Items.Add(db.Name);
}

sys.databases

SELECT name
FROM sys.databases;

Edit:

I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.

public List<string> GetDatabaseList()
{
    List<string> list = new List<string>();

    // Open connection to the database
    string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";

    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();

        // Set up a command with the given query and associate
        // this with the current connection.
        using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
        {
            using (IDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    list.Add(dr[0].ToString());
                }
            }
        }
    }
    return list;

}