【问题标题】:DataGridView Does not refresh after editing in c#在c#中编辑后DataGridView不刷新
【发布时间】:2015-07-12 20:08:43
【问题描述】:

我有一个数据网格视图,它的数据源在加载以下函数后被分配了一个项目列表:

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

还有一个编辑按钮,点击后会执行以下操作:

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

即打开一个编辑表单并将refreshGrid() 分配给它的结束事件。

在那个编辑表单上,我有这个 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();
    }

项目编辑正在工作,但只有在关闭并重新打开编辑表单后才明显,即分配给其关闭事件的 refreshGrid() 方法不起作用!

我该如何解决这个问题?

【问题讨论】:

  • 它不工作还是没有被调用?你经历过哪些错误行为?例外?数据有误?
  • @PaoloCosta,我认为它没有被调用,因为同样的方法适用于我的AddForm。或者,问题出在 EntityFramework Context 类上。也许它在调用刷新方法后正在保存。没有例外,没有错误的数据。一切正常,除了数据网格视图不会更新,除非它被关闭并重新打开

标签: c# winforms entity-framework datagridview


【解决方案1】:

我发现了自己的错误。错误是使用了 Context 类的两个不同实例。

解决方案是添加:

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

就在刷新发生之前。

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 2016-12-23
    • 2013-09-04
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多