20

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity

The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity

private void frmConfig_Load(object sender, EventArgs e)
{
    try
    {
        string Conn = "server=servername;User Id=userid;" + "pwd=******;";
        con = new SqlConnection(Conn);
        con.Open();

        da = new SqlDataAdapter("SELECT * FROM sys.database", con);
        cbSrc.Items.Add(da);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

I am trying to do this but it is not generating any data

3
  • What are you really stuck on? Getting the list of databases? or, figuring out how to use a combo box? (If it is both, then you might be better splitting this into two questions) Commented Dec 4, 2012 at 12:46
  • The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity Commented Dec 4, 2012 at 12:56
  • You have misspelled "sys.databases" Commented May 25, 2023 at 17:44

8 Answers 8

44

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;

}
Sign up to request clarification or add additional context in comments.

4 Comments

The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
It was not the exact answer but i got the answer with the help of ur example thanks chris
how can we get the same list using EF?
@NaveenKumar Try this out
12

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);
}

8 Comments

for more information you can see this question
tried this but the min I reference the connectioninfo.dll I get "Cannot find type System.SystemException in module CommonLanguageRuntimeLibrary." build error.
why this solution doesn't work in ASP.net MVC project ?
@Amir it is the same code as about which is working fine with desktop application but doesn't work in ASP.net MVC project
@Motaz do you have access to instance Or throw exception?
|
3

you can use on of the following queries:

  • EXEC sp_databases
  • SELECT * FROM sys.databases

Serge

Comments

2

Simply using GetSchema method:

using (SqlConnection connection = GetConnection())
{
    connection.Open();
    DataTable dtDatabases = connection.GetSchema("databases");

    //Get database name using dtDatabases["database_name"]
}

Comments

0
    using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
    {
        connection.Open();
        var command = new System.Data.SqlClient.SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
        command.CommandText = "SELECT name FROM master.sys.databases";

        var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
        var dataset = new DataSet();
        adapter.Fill(dataset);
        DataTable dtDatabases = dataset.Tables[0];
    }

Comments

0
   How to get list of all database from sql server in a combobox using c# asp.net windows application  
     try
        {
            string Conn = "server=.;User Id=sa;" + "pwd=passs;";
            SqlConnection con = new SqlConnection(Conn);
            con.Open();

            SqlCommand cmd = new SqlCommand();
         //   da = new SqlDataAdapter("SELECT * FROM sys.database", con);
            cmd = new SqlCommand("SELECT name FROM sys.databases", con);
           // comboBox1.Items.Add(cmd);
            SqlDataReader dr;
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //comboBox2.Items.Add(dr[0]);
                    comboBox1.Items.Add(dr[0]);
                }
            }

           // .Items.Add(da);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

1 Comment

Please consider adding some explanation and details to your answer.
0

Try this:

SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    cbSrc.Items.Add(dr[0].ToString());
}
con.Close();

or this:

DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}

Comments

0
   public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{

        List<string> lstDatabaseNames = null;

        try
        {
            lstDatabaseNames = new List<string>();
            //string servername = System.Environment.MachineName;
            string newConnString = string.Format("Data Source={0};", ServerName);

            if (UserID == null)
            {
                newConnString += "Integrated Security = True;";
            }
            else
            {
                newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
            }
            SqlConnection con = new SqlConnection(newConnString);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            foreach (DataRow row in dt.Rows)
            {
                lstDatabaseNames.Add(row[0].ToString());
            }
            con.Close();
            return lstDatabaseNames;
        }
        finally
        {
   
        }
    }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.