c# - DataGridView AllowUserToAddRow 属性不起作用

标签 c# linq entity-framework datagridview bindingsource

我有一个使用 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() 并具体化了您的查询 - 这似乎破坏了完整的数据绑定(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/

相关文章:

c# - 如何通过添加新属性将 DataGridView 列文本格式设置为大写?

c# - 如何将字符串发送到其他应用程序,包括 Microsoft Word

c# - 如果适用,将嵌套的 ForEach 替换为 Select

c# - 如何使用 List<String> 变量过滤强类型列表

c# - 无法跟踪实体类型 Model 的实例,因为已经在跟踪另一个具有相同键值 {'Id' } 的实例

c# - 在 Outlook mailitem.To 字段中设置焦点使用 c#?

c# - 使用什么算法来检查一组是否与另一组重叠?

c# - 匿名类型和 Null

asp.net-mvc - 首先使用实体​​框架模型/数据库进行MVC3验证

.net - 从存储过程创建 Entity Framework 对象