I've tried to make the ComboBox
refresh itself after I click the delete button, but when I try this it gives me the error:
Items collection cannot be modified when the DataSource property is set.
This is the code from the Delete
button:
private void deleteBttn_Click(object sender, EventArgs e)
{
con.Open();
string Query = "DROP TABLE [" + comboBox1.SelectedValue.ToString() + "]";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myReader;
try
{
myReader = cmd.ExecuteReader();
MessageBox.Show("Deleted");
this.comboBox1.Items.Remove(this.comboBox1.SelectedItem);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
And this is the code from the ComboBox
:
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select TABLE_NAME from INFORMATION_SCHEMA.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Setting the DataSource-Property automatically pairs the ComboBox to the database table and prevents you from manually modifying just the GUI-element.
To force a refresh of the ComboBox (although you might not need to, seeing how the Form should handle it) try this:
comboBox1.DataSource = null;
comboBox1.DataSource = dtRecord;