如果用户选择已更改,则清除Combobox中的项目

时间:2011-09-29 15:45:51

标签: c# winforms

我正在开发一个windowsform应用程序。它由一个带有服务器名列表的组合框和一个用于所选服务器名的数据库列表以及一个用于所选数据库的表列表的组合框组成。当用户选择servername并单击按钮时,它会在服务器中显示数据库名称。如果用户改变主意并选择另一个服务器名称,我仍然拥有相同的第一个数据库列表。我的数据库列表应该每次都刷新,具体取决于服务器选择的变化,我该怎样才能实现这个

以下是我的示例代码:

   public MainForm()
    {
        InitializeComponent();
        // FileHelper = new SqlDatabaseDataExport.FileHelper.FileUtilHelper();
        dt = SmoApplication.EnumAvailableSqlServers(false);

        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                ServernamesList_combobox.Items.Add(dr["Name"]);

            }
           // ServernamesList_combobox.Items.Add("10.80.104.30\\webx");

            DisplayMainWindow("Server list added");
            Logger.Log("Server List added");
        }

        Authentication_combobox.Items.Add("Windows Authentication");
        Authentication_combobox.Items.Add("Sql Authentication");
    }



    /// <summary>
    /// Generating list of databases with in the selected Server and list of 
    /// selected tables with in the selected 
    /// databse
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    private void DatabasenamesList_combobox_SelectedIndexChanged(object sender, EventArgs e)
    {

        dbName = DatabasenamesList_combobox.SelectedItem.ToString();


        connectionString = GetConnectionString();
        string mySelectQuery = "select [name] from sys.tables WHERE type = 'U' AND is_ms_shipped = 0 ORDER BY [name];";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand myCommand = new SqlCommand(mySelectQuery, con);

        con.Open();
        SqlDataReader myReader = myCommand.ExecuteReader();
        try
        {
            while (myReader.Read())
            {
                SelectTables.Items.Add(myReader.GetString(0));
            }
        }
        finally
        {

            myReader.Close();
            con.Close();
        }


    }



      private void button1_Click_1(object sender, EventArgs e)
    {
        serveName = ServernamesList_combobox.SelectedItem.ToString();
        if (string.IsNullOrEmpty(serveName))
        {
            MessageBox.Show("Please select servername");
            return;
        }

        if (Authentication_combobox.SelectedItem == null)
        {
            MessageBox.Show("Please select authentication");
            return;
        }
        String conxString = string.Empty;

        if (Authentication_combobox.SelectedItem == "Windows Authentication")
        {
            conxString = "Data Source=" + serveName + "; Integrated Security=True;";
        }

        if (Authentication_combobox.SelectedItem == "Sql Authentication")
        {
            if (string.IsNullOrEmpty(Username.Text))
            {
                MessageBox.Show("Please Enter Valid User name");
                return;
            }
            if (string.IsNullOrEmpty(Password.Text))
            {
                MessageBox.Show("Please Enter Valid Password");
                return;
            }
            conxString = "Data Source=" + serveName + "; Integrated Security=False;User ID =" + Username.Text + ";Password=" + Password.Text;
        } 


        using (SqlConnection sqlConx = new SqlConnection(conxString))
        {

            try
            {
                sqlConx.Open();
                MessageBox.Show("Connection established successfully");

            }
            catch (Exception ex)
            {

                MessageBox.Show("Exception" + ex);
                MessageBox.Show(" Please enter valid Credentials");
                return;

            }

            DataTable tblDatabases = sqlConx.GetSchema("Databases");
            sqlConx.Close();

            foreach (DataRow row in tblDatabases.Rows)
            {
                Databases.Add(row["database_name"].ToString());
            }

        foreach (var database in Databases)
        {
            DatabasenamesList_combobox.Items.Add(database);
        }


    }

  }

1 个答案:

答案 0 :(得分:3)

将SelectedIndexChanged事件添加到DatabasenamesList_combobox。 在该方法的代码中,只需调用代码来填充数据库。右边任何东西塞进'button1'。将您的程序移到一个名为

的程序中

private void PopulateDatabases(string serverName)
{
        //populate Databases
        //.. your code here ...

        //clear the list
        DatabasenamesList.Items.Clear();
        foreach (var database in Databases)
        {
            DatabasenamesList_combobox.Items.Add(database);
        }

}

还有许多其他方法可以清理此代码,例如: catch(Exception ex)

您如何知道异常是因为没有正确的身份验证类型?您应该捕获特定类型的异常并单独处理。