[英]DataGridView Does not refresh after editing in c#
我有一个数据网格视图,该数据网格视图在加载以下功能后为其数据源分配了一个项目列表:
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()
事件分配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()
,即分配给其关闭事件的refreshGrid()
方法不起作用!
我怎样才能解决这个问题?
我发现了自己的错误。 错误是使用了Context类的两个不同实例。
解决方案是添加:
SomsaContext database = new SomsaContext(); // i.e. new instance of Context class
在刷新发生之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.