在 Windows Forms 專案中,使用 SqlDataAdapter 填充 DataSet 並繫結至 DataGridView 後,若資料庫資料已更新(如新增/刪除/修改),再次呼叫同一個查詢方法,DataGridView 可能不會自動顯示最新資料,需明確呼叫 DataGridView.Refresh() 或重新設定 DataSource。
public void ComonDataView_order_info() {
// ... 連線、建立 DataAdapter、Fill DataSet ...
dataGridView1.DataSource = order_info_ds.Tables[0].DefaultView;
// 缺少重新整理觸發
}
dataGridView1.Refresh(); 強制重繪控制項,讀取當前 DataSource 最新內容。dataGridView1.DataSource = null;
dataGridView1.DataSource = order_info_ds.Tables[0].DefaultView;DataBindingComplete 事件,確保 UI 與資料同步。var bs = new BindingSource();
bs.DataSource = order_info_ds.Tables[0];
dataGridView1.DataSource = bs;
// 更新時
bs.ResetBindings(false);DataAdapter.Update() 是將 DataSet 變更寫回資料庫,而非從資料庫重新讀取。AcceptChangesDuringFill = true 僅影響 Fill 過程中行狀態,不影響 UI 重繪。Invoke 回 UI 執行緒重新整理。public void ComonDataView_order_info() {
try {
DBConnect();
using (var da = new SqlDataAdapter("select * from 訂單詳情", sqlCon))
using (var ds = new DataSet()) {
da.Fill(ds);
dataGridView1.DataSource = null;
dataGridView1.DataSource = ds.Tables[0].DefaultView;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.Refresh(); // 確保立即重繪
}
} catch (Exception ex) {
MessageBox.Show("錯誤:" + ex.Message);
} finally {
if (sqlCon.State == ConnectionState.Open) sqlCon.Close();
}
}
掌握 DataGridView 資料繫結的重新整理機制,能確保使用者隨時看到最新的資料庫狀態。