【问题标题】:How to get the DataSource name in dropdownlist control in C# Winforms如何在 C# Winforms 的下拉列表控件中获取数据源名称
【发布时间】:2014-01-03 10:52:59
【问题描述】:

您好,我正在开发一个应用程序来将数据从一个系统检索到另一个远程系统。

为此,我首先通过下面的屏幕设置应用程序的连接字符串。

当我从第一个 dropdownlist 选择 SQL Server 时,我需要可用的 DataSource namedatabase instance namesa 或任何安装数据库的东西,应该排在第二个 dropdownlist 和当我选择DataSource availabledatabase name 应该在第三个提示dropdownlist

我不知道该怎么做。目前我正在手动执行此操作,但它既费时又容易出错。

我们如何解决它,MySql 也是如此。

【问题讨论】:

    标签: c# mysql winforms connection-string


    【解决方案1】:

    您可以使用以下代码获取数据库实例名称

    SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            System.Data.DataTable table = instance.GetDataSources();
            foreach (System.Data.DataRow row in table.Rows)
            {
                cboServerName.Items.Add(row["ServerName"]);
            }
    

    对于该服务器中的数据库,您可以使用此代码

    SqlConnection SqlCon = new SqlConnection("server=" + cboServerName.SelectedItem.ToString() + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text);
            try
            {
                SqlCon.Open();
                //if connection was successful,fetch the list of databases available in that server
                SqlCommand SqlCom = new SqlCommand();
                SqlCom.Connection = SqlCon;
                SqlCom.CommandType = CommandType.StoredProcedure;
                SqlCom.CommandText = "sp_databases";        //sp_databases procedure used to fetch list of available databases
    
                SqlDataReader SqlDR;
                SqlDR = SqlCom.ExecuteReader();
    
                while (SqlDR.Read())
                {
                    cboDatabase.Items.Add(SqlDR.GetString(0));
                }
            }
            catch
            {
                MessageBox.Show("Connection Failed...Please check username and password","Error");
            }
    

    【讨论】:

    • 非常感谢您的解决方案..非常完美..您知道我们如何在 MySQL 上做到这一点吗..??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2021-01-24
    • 2015-12-12
    • 1970-01-01
    • 2017-06-24
    • 2015-06-01
    • 1970-01-01
    相关资源
    最近更新 更多