Jevon Jevon - 22 days ago 6
SQL Question

refreshing comboBox after creating a new table in database

In my code I created a table and exported a CSV file to it. in another section of my code the comboBox is populated with the table names from my database. This is shown below:

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


What am trying to achieve is to refresh the comboBox as to reflect the newly added table which was executed through the above function. What came to mind first was to create a button and rewrite the above function like this:

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


As you guessed, it works but the values are duplicated. How do I refresh the comboBox without duplicating the existing info?

Answer

As I mentioned at comments you can clear items before recall method with,

combobox.Items.Clear();

Or you can add If statement at while loop like this,

while (dr2.Read())
{
      int col = dr2.GetOrdinal("TABLE_NAME");
      if (!comboBox1.Items.Contains(dr2[col].ToString()))
      {
          comboBox1.Items.Add(dr2[col].ToString());
      }
}

So you don't need to clear items every recall.

Hope helps,