Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在数据库中创建新表后刷新组合框_C#_Sql_Winforms - Fatal编程技术网

C# 在数据库中创建新表后刷新组合框

C# 在数据库中创建新表后刷新组合框,c#,sql,winforms,C#,Sql,Winforms,在我的代码中,我创建了一个表并向其中导出了一个CSV文件。在代码的另一部分中,组合框中填充了数据库中的表名。如下所示: private void FillCombo() { try { string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";

在我的代码中,我创建了一个表并向其中导出了一个CSV文件。在代码的另一部分中,组合框中填充了数据库中的表名。如下所示:

private void FillCombo()
    {
        try
        {

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            using (SqlConnection con2 = new SqlConnection(connectionString))
            {
                con2.Open();
                string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
                SqlCommand cmd2 = new SqlCommand(query, con2);

                SqlDataReader dr2 = cmd2.ExecuteReader();
                while (dr2.Read())
                {
                    int col = dr2.GetOrdinal("TABLE_NAME");
                    comboBox1.Items.Add(dr2[col].ToString());
                }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
我试图实现的是刷新组合框,以反映通过上述函数执行的新添加的表。首先想到的是创建一个按钮并重写上述函数,如下所示:

 private void button1_Click_1(object sender, EventArgs e)
    {
        //this is where I would just rewrite the contents of the above function
    }

正如您所猜测的,它可以工作,但值是重复的。如何在不复制现有信息的情况下刷新组合框?

正如我在评论中提到的,您可以在调用方法之前清除项目

combobox.Items.Clear();
或者可以在while循环中添加If语句,如下所示

while (dr2.Read())
{
      int col = dr2.GetOrdinal("TABLE_NAME");
      if (!comboBox1.Items.Contains(dr2[col].ToString()))
      {
          comboBox1.Items.Add(dr2[col].ToString());
      }
}
所以你不需要每次召回都清除物品


希望有帮助,

首先清除项目?如果您的意思是
comboBox1.ResetText()
则执行命令,然后执行相同的结果,复制@berkay他的意思是
comboBox1.items.Clear()
-将其放在
FillCombo
的顶部,然后从按钮单击处理程序调用
FillCombo
。不,在调用方法之前,请像这样清除combobox项,
combobox.items.clear()欢迎您,请查看答案,还有一个选项。您的第二个解决方案不处理删除或重命名的表-如果可能的话。是的,您是对的,只处理新添加的表@大胡子