DataGridView AllowUserToAddRow属性不起作用

我有一个带有Entity Framework的简单项目,我在Form有一个DataGridView ,我将其AllowUserToAddRow属性设置为true但我仍然无法在其中添加新行。

这是我的代码:

 DBEntities context = new DBEntities(); private void Form1_Load(object sender, EventArgs e) { var q = (from i in context.myTable select i).ToList(); DataGridView.DataSource = q; } private void btnSave_Click(object sender, EventArgs e) { context.SaveChanges(); MessageBox.Show("saved successfully"); } 

如果我使用BindingSource控件,它允许我在DataGridView插入行,但在我调用context.SaveChanges()后,在我的数据库文件中没有插入任何内容。 所以我想也许它的相对于这个问题, DataGridViewtrue AllowUserToAddRow属性不允许我在DataGridView插入行。

您的问题是您调用.ToList()并实现查询 – 这似乎打破了完整的数据绑定。

应该能够简单地:

 DBEntities context = new DBEntities(); private void Form1_Load(object sender, EventArgs e) { var q = (from i in context.myTable select i); DataGridView.DataSource = q; } 

我试过这个并且它适用于允许新行(你需要在你的表中有一个主键,但你应该有这个)。


请注意:在Entity Framework 4.1中故意破坏了此行为 – Webforms数据绑定与EF Code-First Linq查询错误


我说应该在我的回答中,因为我真的有点惊讶这很容易。 我记得它在早期版本的Entity Framework中工作得并不好,我没有非常使用4.0。

如果上面的解决方案不起作用,您可能必须以困难的方式执行此操作并在保存之前自己添加新对象:

首先介绍一个绑定源,当您保存时执行类似的操作(在示例中使用Customer的虚构实体):

 foreach (Customer customer in bs.List) { // In my db customerId was an identity column set as primary key if (customer.CustomerId == 0) context.Customers.AddObject(customer); } context.SaveChanges(); 

我从4开始痛苦地升级到EF 6,我遇到了类似的问题,EF6中的解决方案如下,我已经展示了where声明以获得进一步的帮助。

 DBEntities context = new DBEntities(); private void Form1_Load(object sender, EventArgs e) { context.MyTable.Where(e => e.myField == 1).Load(); BindingSource bs = new BindingSource(); bs.DataSource = context.MyTable.Local.ToBindingList(); myDatagridView.DataSource = bs; } 

你现在可以使用context.SaveChanges(); 保存更改或插入

我对Interbase方言的自定义数据库实现有类似的问题。 我的解决方案类似于上面的解决方案:

 var tableAList = _dbImplementation.SelectAll().ToList(); var bindingSource = new BindingSource(); bindingSource.DataSource = typeof (TableA); foreach (var tableA in tableAList) { bindingSource.Add(tableA); } dataGridView.DataSource = bindingSource; 

有用的参考: 详细的数据绑定教程

如果要将dataGridView绑定到源,则插入行的唯一合适方法是向DataGridView绑定到的数据结构添加行。