2016-10-22 37 views
0

如何在數據網格視圖中立即顯示數據插入或更新。我要重新啓動該項目表明,Data.I使用更新()刷新()但不是爲我工作如何在插入或更新後更新DataGridview

private void UpdateDebtbutton_Click(object sender, EventArgs e) { SqlConnection conn = ForConnection(); conn.Open(); using (conn) { if (paytextBox.Text != "") { SqlCommand cmd = new SqlCommand("spdebth", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id", SqlDbType.Int).Value =customerIDTextBox.Text.ToString(); cmd.Parameters.Add("@text", SqlDbType.Int).Value = paytextBox.Text.ToString(); cmd.ExecuteNonQuery(); MessageBox.Show("Record updated"); spSelectAllCustomerDataGridView.Update(); spSelectAllCustomerDataGridView.Refresh(); conn.Close(); } } }

+0

再次設置數據源。 – Berkay

+0

@Berkay謝謝你親愛的現在工作 –

+0

使用DatatGridView的DataTable你嘗試過dataTable.AcceptChanges(); – JohnG

回答

0

RefreshUpdate方法不用於刷新數據,但重新塗漆WinForms控制。

有顯示在DataGridView中的數據更新的一些方法:

  1. 使用BindingList作爲數據源,但是這需要一個對象上DataGridView實施INotifyPropertyChanged
  2. 更新行手動
  3. 重新綁定DataSource

下面是例如用於第三點:

private void UpdateDebt(int customerId, int debt) 
{ 
    var debts = (List<Debt>)spSelectAllCustomerDataGridView.DataSource; 
    var item = debts.First(x => x.Id == customerId); 
    item.Debt = debt; 

    spSelectAllCustomerDataGridView.DataSource = null; 
    spSelectAllCustomerDataGridView.DataSource = debts; 
} 

您必須重新綁定DataGridView以顯示更改。