简体   繁体   English

在C#中编辑后,DataGridView不刷新

[英]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. 即打开一个编辑表单,并为其refreshGrid()事件分配refreshGrid()

On that Edit Form I have this Save button which does this: 在该“编辑表单”上,我有一个“ Save按钮,可以执行以下操作:

    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! 项目编辑有效,但仅在关闭并重新打开编辑表单refreshGrid() ,即分配给其关闭事件的refreshGrid()方法不起作用!

How can I fix this? 我怎样才能解决这个问题?

I found my own mistake. 我发现了自己的错误。 The mistake was using two different instances of Context class. 错误是使用了Context类的两个不同实例。

The solution was to add: 解决方案是添加:

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

right before the refresh takes place. 在刷新发生之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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