我有一个使用 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()
之后使用这种方法> 我的数据库文件中没有插入任何内容。所以我认为可能与这个问题相关的是 DataGridView
和 true
AllowUserToAddRow
属性不允许我在 DataGridView< 中插入行
.
最佳答案
您的问题是您调用了 .ToList()
并具体化了您的查询 - 这似乎破坏了完整的数据绑定(bind)。
您应该能够简单地拥有:
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 data binding with EF Code-First Linq query error
我在回答中说应该,因为实际上我有点惊讶它这么简单。我记得它在 Entity Framework 的早期版本中工作得不是很好,我也没有经常使用 4.0。
如果上面的解决方案不起作用,您可能必须以困难的方式执行此操作并在保存之前自己添加新对象:
首先引入一个绑定(bind)源,然后在保存时执行类似的操作(在示例中使用一个虚构的实体 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();
关于c# - DataGridView AllowUserToAddRow 属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11799661/