C# 在c中编辑后,DataGridView不会刷新#
我有一个数据网格视图,其数据源在加载以下函数后被分配一个项目列表:C# 在c中编辑后,DataGridView不会刷新#,c#,winforms,entity-framework,datagridview,C#,Winforms,Entity Framework,Datagridview,我有一个数据网格视图,其数据源在加载以下函数后被分配一个项目列表: public void refreshGrid(object sender, FormClosingEventArgs e) { dgvItems.SuspendLayout(); itemBindingSource.SuspendBinding(); List<Item> items = db.Items.ToList(); // db is MyContext db = new MyCo
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();
}
i、 e.打开一个编辑表单,并将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()
方法不工作
我怎样才能解决这个问题?我发现了自己的错误。错误在于使用了上下文类的两个不同实例 解决办法是增加:
SomsaContext database = new SomsaContext(); // i.e. new instance of Context class
就在刷新发生之前。它不工作或未调用?你经历过什么错误行为?例外?错误的数据?@PaoloCosta,我认为它没有被调用,因为相同的方法适用于我的
AddForm
。或者,问题在于EntityFramework上下文类。可能在调用refresh方法后正在保存。没有例外,没有错误的数据。一切正常,除了datagrid视图在关闭和重新打开之前不会更新
SomsaContext database = new SomsaContext(); // i.e. new instance of Context class