Ahmad Raza Ahmad Raza - 1 month ago 10
C# Question

How To Show DataGridview Updated After insertion Or Updation

How To show Data Immediately In Data Grid View That is inserted Or Updated. I have to Re Start The Project To Show That Data.I Used Update() And Refresh() But not working for me

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

Answer

Refresh and Update methods are not used to refresh data, but re-paint WinForms control.

There are some ways of displaying data updated in DataGridView:

  1. Use BindingList as data source, but this requires a object to implement INotifyPropertyChanged
  2. Update row on DataGridView manually
  3. Rebind DataSource

Below is example for third point:

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

You have to rebind DataGridView to display changes.

Comments