简体   繁体   English

如何在C#Winforms的dropdownlist控件中获取数据源名称

[英]How to get the DataSource name in dropdownlist control in C# Winforms

Hi I am developing an application to retrieve data from one system to another remote system. 嗨,我正在开发一个应用程序,以将数据从一个系统检索到另一个远程系统。

To do this I am firstly setting the connection string of the application by below screen. 为此,我首先在屏幕下方设置应用程序的连接字符串。

控制面板

When I chose the SQL Server from first dropdownlist I need that the available DataSource name or database instance name like sa or anything by witch the database installed, should be come in second dropdownlist and again when I select DataSource available , database name should be prompt in 3rd dropdownlist . 当我从第一个dropdownlist选择SQL Server时,我需要将可用的DataSource namedatabase instance name例如sa或安装database name放在第二个dropdownlist并且再次选择“ DataSource available ,应在以下位置提示database name第三dropdownlist

I don't have any idea about this how can I do this. 我对此一无所知。 Currently I am doing this manually but it's time consuming and error prone. 目前,我正在手动执行此操作,但是这很耗时且容易出错。

How can we resolve it and also for MySql too. 我们如何解决它以及MySql也是如此。

You can get the database instance name using following code 您可以使用以下代码获取数据库实例名称

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

and for the databases in that server you can use this code 对于该服务器中的数据库,您可以使用此代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM