如何使用C#.net从组合框中的SQL Server获取所有数据库的列表 [英] How to get list of all database from sql server in a combobox using c#.net

查看:77
本文介绍了如何使用C#.net从组合框中的SQL Server获取所有数据库的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过文本框输入源名称userid和密码,并希望数据库列表应在组合框中列出,以便用户可以选择所有四个选项sourcename,userid,password和databasename来执行连接

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

应根据用户从其他系统中检索数据库。用户将输入IP,用户名和密码,他们将在组合框中获得数据库列表,以便他们可以选择所需的数据库并执行连接

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

推荐答案

sys.databases

SELECT name
FROM sys.databases;

编辑:

我建议使用IDataReader ,返回列表并缓存结果。您可以简单地将下拉列表绑定到结果,并在需要时从缓存中检索相同列表。

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;

}

这篇关于如何使用C#.net从组合框中的SQL Server获取所有数据库的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆