DataGridView AllowUserToAddRow 属性不起作用

Mas*_*arz 5 c# linq entity-framework datagridview bindingsource

我有一个使用实体框架的简单项目,我有一个DataGridViewForm并将其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");
}
Run Code Online (Sandbox Code Playgroud)

如果我使用BindingSource控件,它允许我插入行,DataGridView但是在context.SaveChanges()我在数据库文件中不调用任何插入之后,使用这种方法。所以我想也许与这个问题有关,DataGridView属性true AllowUserToAddRow不允许我在 中插入行DataGridView

Dav*_*all 2

您的问题是您调用.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;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,它可以很好地允许新行(您确实需要在表中拥有主键,但无论如何您都应该拥有它)。


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


我在回答中说应该是因为我实际上有点惊讶它是如此简单。我记得它在实体框架的早期版本中运行得不太好,而且我也没有经常使用 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();
Run Code Online (Sandbox Code Playgroud)