DataGridView AllowUserToAddRow property doesn't work

后端 未结 4 673
离开以前
离开以前 2020-12-06 14:52

I have a simple project with Entity Framework, I have a DataGridView in my Form and I set its AllowUserToAddRow property to true

4条回答
  •  孤街浪徒
    2020-12-06 15:01

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

    You should be able to simply have:

    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).


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


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

提交回复
热议问题