简体   繁体   中英

DataGridView Does not refresh after editing in c#

I have a data grid view whose data source gets assigned a list of items after the following function on load:

public void refreshGrid(object sender, FormClosingEventArgs e)
{
    dgvItems.SuspendLayout();
    itemBindingSource.SuspendBinding();
    List<Item> items = db.Items.ToList();  // db is MyContext db = new MyContext();
    itemBindingSource.DataSource = items;
    dgvItems.DataSource = null;
    dgvItems.DataSource = itemBindingSource;
    itemBindingSource.ResumeBinding();
    dgvItems.ResumeLayout();
}

private void AllItemsForm_Load(object sender, EventArgs e)
{
   refreshGrid();
}

and there is a edit button which does the following on click:

private void btnEditItem_Click(object sender, EventArgs e)
{
    Item item = (Item)dgvItems.SelectedRows[0].DataBoundItem;
    var editForm = new EditItemForm(item);
    editForm.FormClosing += new FormClosingEventHandler(refreshGrid);
    editForm.Show();
}

ie opens an edit form and assigns refreshGrid() to its closing event.

On that Edit Form I have this Save button which does this:

    private void btnSave_Click(object sender, EventArgs e)
    {
        Item itemEdited = db.Items.Where(i => i.itemId == itemEditing.itemId).Single();
        itemEdited.categoryId = (int)cbxCategory.SelectedValue;
        itemEdited.description = tbxDescription.Text;
        itemEdited.price = (Double)nudPrice.Value;
        db.Entry(itemEdited).State = EntityState.Modified;
        db.SaveChanges();
        this.Close();
    }

the item edit is working, but is apparent only after closing and reopening the edit form, ie that refreshGrid() method which was assigned to its closing event is not working!

How can I fix this?

I found my own mistake. The mistake was using two different instances of Context class.

The solution was to add:

SomsaContext database = new SomsaContext();  // i.e. new instance of Context class

right before the refresh takes place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM