【问题标题】:C# Return List of Databases in ComboboxC# 返回 Combobox 中的数据库列表
【发布时间】:2018-10-11 09:27:36
【问题描述】:

我有两个组合框,comboBoxSelectServercomboBoxSelectDatabase

根据在comboBoxSelectServer 中选择的值,当用户单击comboBoxSelectDatabase 时,他们将从该服务器获取各种数据库。

但是,在运行应用程序时,comboBoxSelectDatabase 中没有返回任何数据库。

我认为这是由于我的代码的以下部分,因为在调试时它不会拉回任何东西。

comboBoxSelectDatabase.Items.Add(command);

我在下面包含了我的代码;

if (comboBoxSelectServer.SelectedIndex == 0)
{
    string commandTextSERV1 = "SELECT name FROM master.sys.databases " +
                              "where name LIKE 'Client_%'";

    string connectionString = Properties.Settings.Default.connectionStringSERV1;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandTextSERV1, con);

        try
        {
            con.Open();
            command.ExecuteNonQuery();
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                comboBoxSelectDatabase.Items.Add(command);
            }
            else
            {
                MessageBox.Show("Error");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
}

【问题讨论】:

  • 我认为您的问题与comboBoxSelectDatabase.Items.Add(command); 有关。在这里,您将 SqlCommand 对象而不是任何返回的 DataRows 添加到下拉列表中
  • @JayV 是的,我也这么认为..但我不知道用什么替换它来拉回数据库列表。我已经尝试了一些选项,但到目前为止没有任何效果..
  • google一下executereader附带的例子

标签: c# sql database winforms combobox


【解决方案1】:
comboBoxSelectDatabase.Items.Add(command);

错了,应该是:

while (reader.Read())
{
    comboBoxSelectDatabase.Items.Add(reader["name"].ToString());
}

【讨论】:

    【解决方案2】:

    问题在于您的以下陈述。在这里,您添加的是命令对象,而不是阅读器行。

    comboBoxSelectDatabase.Items.Add(command);
    

    改成

    while (reader.Read())
    {
        comboBoxSelectDatabase.Items.Add(Convert.ToString(reader["name"]));
    }
    

    这应该用数据库名称填充组合框。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 2014-11-29
      • 2015-05-19
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多