DataGridView的AllowUserToAddRow属性不起作用 [英] DataGridView AllowUserToAddRow property doesn't work
问题描述
我有2个问题。
第一个问题是我有一个简单的项目实体框架,我有一个 DataGridView的
在我的表格
,我设置其 AllowUserToAddRow
属性真正
但我仍然不能添加新行到它。
First problem is 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.
的这里是截图,看看我的 DataGridView的
看起来像在运行时。
Here is a screenshot to see how my DataGridView
looks like in run-time.
这是我的代码:
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的
与真正
AllowUserToAddRow
属性不会让我在 DataGridView的
插入一行。
Second problem is 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被有意打破Web表单数据和EF代码优先Linq查询错误
Do Note: this behaviour has been intentionally broken in Entity Framework 4.1 - Webforms data binding with EF Code-First Linq query error
我说的应在我的答案,因为我其实是有点惊讶正是这种容易。我记得它不是在早期版本的实体框架的工作这么好,我没有用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:
先介绍一个绑定源并在保存像做(与客户在例如一个假想的实体):
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屋!