DataGridView AllowUserToAddRow 属性不起作用 [英] DataGridView AllowUserToAddRow property doesn't work

查看:23
本文介绍了DataGridView AllowUserToAddRow 属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的实体框架项目,我的 Form 中有一个 DataGridView,我将它的 AllowUserToAddRow 属性设置为 是的 但我仍然无法向其中添加新行.

I have a simple project with Entity Framework, I have a DataGridView in my Form and I set its AllowUserToAddRow property to true but still I can not add new rows into it.

这是我的代码:

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.

If I use a BindingSource control, it allow me to insert rows in DataGridView but with this approach after I call context.SaveChanges() nothing insert in my database file. So I thought maybe its relative to this problem that DataGridView with true AllowUserToAddRow property doesn't let me to insert row in DataGridView.

推荐答案

您的问题是您调用 .ToList() 并具体化您的查询 - 这似乎破坏了完整的数据绑定.

Your problem is that you call .ToList() and materialize your query - this appears to break the full databinding.

应该能够:

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

我试过这个,它在允许新行时工作得很好(你的表中确实需要有一个主键,但无论如何你应该有).

I tried this and it works fine for allowing new rows (you do need to have a primary key in your table but you should have that anyway).

请注意:此行为已在实体框架 4.1 中被有意破坏 - Webforms 数据绑定与 EF Code-First Linq 查询错误

Do Note: this behaviour has been intentionally broken in Entity Framework 4.1 - Webforms data binding with EF Code-First Linq query error

我在回答中说应该,因为我实际上有点惊讶它这么容易.我记得它在 Entity Framework 的早期版本中运行得不是很好,而且我没有经常使用 4.0.

I say should in my answer because I'm actually a little surprised it is this easy. I recall it not working so nicely in earlier versions of Entity Framework and I haven't used 4.0 very much.

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

If the solution above doesn't work you may have to do this the hard way and add new objects yourself before saving:

首先引入一个绑定源,然后在保存时执行以下操作(在示例中使用虚构的 Customer 实体):

First introduce a binding source and when you save do something like (with an imaginary entity of Customer in the example):

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();

这篇关于DataGridView AllowUserToAddRow 属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆