[英]Refresh ComboBox
單擊刪除按鈕后,我嘗試使ComboBox
刷新,但是當我嘗試執行此操作時,出現以下錯誤:
設置DataSource屬性后,將無法修改項目集合。
這是“ Delete
按鈕中的代碼:
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();
}
這是來自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);
}
設置DataSource屬性后,將無法修改項目集合。
該錯誤消息告訴您,您已在“ comboBox1”上設置了DataSource
屬性。 因此,您應該刪除DataSource
:
comboBox1.DataSource = null;
或者,如果您想保留DataSource
,請不要嘗試自己刪除項目(您應該在dataSource表中,而不是comboBox項目中)
設置DataSource-Property會自動將ComboBox與數據庫表配對,並阻止您僅手動修改GUI元素。
要強制刷新ComboBox(盡管您可能不需要,請參見Form如何處理它),請嘗試以下操作:
comboBox1.DataSource = null;
comboBox1.DataSource = dtRecord;
據我了解,您的ComboBox上有一個表格列表,您想刪除所選的項目:
第一件事:如果您使用DDL查詢(如DROP,CREATE,ALTER ..)和某些DML查詢(如DELETE,Update,INSERT ..),則應使用ExecuteNonQuery
方法,而不要像以前那樣使用ExecuteReader
方法
第二:確保將ComboBox控件上的屬性AutoPostBack
設置為true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.