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

前端 未结 6 1029
北荒
北荒 2020-12-13 16:14

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, u

6条回答
  •  庸人自扰
    2020-12-13 16:46

    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 GetDatabaseList()
    {
        List list = new List();
    
        // 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;
    
    }
    

提交回复
热议问题