Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 929
Ajit Nair Avatar asked Dec 04 '12 12:12

Ajit Nair


People also ask

How do you get a list of all SQL servers on the network?

To list all the SQL instances, navigate to the root directory and run the Get-Childitem to get the list. Note: The path SQLSERVER:\SQL\<ServerName> has all the installed SQL instances of the listed server.

What is the query to list all the databases?

The command to see system databases are : SELECT name, database_id, create_date FROM sys.


1 Answers

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;

}
like image 92
Chris Gessler Avatar answered Sep 24 '22 00:09

Chris Gessler