简体   繁体   English

如何通过BindingNavigator在DataBase中插入,更新和删除DataGridView的记录

[英]How to insert, update and delete records of a DataGridView to DataBase via BindingNavigator

I have a Student table and a bunch of other tables in my database called University and I used Entity Framework to connect to it in my winforms application. 我的数据库中有一个Student表和一堆其他表(称为University并且我使用Entity Framework在Winforms应用程序中连接到该表。 我的实体框架模型

I created a DataSource from the Student table inside my Entity Framework model. 我从实体框架模型内的Student表创建了一个DataSource 我的资料来源

then I dragged the DataSource on to my form.(See the pic below) 然后将DataSource拖到我的表单上。(请参见下图)
I know how to populate the records of the student table (here is just one record in my DB) into the DataGridView , with no problem using this piece of code: 我知道如何将student表的记录(在我的数据库中只有一条记录)填充到DataGridView ,使用这段代码没有问题:

//An instance of my EFModel
    Oublic UniversityEntities UE = new UniversityEntities();
 private void Form1_Load_1(object sender, EventArgs e)
    {
        studentBindingSource.DataSource = UE.Students.ToList();
    }

我的表格

But I want to use BindingNavigator to insert/update/delete records from/to the database and I don't khow how it's possible, considering that I use Entity Framework. 但是我想使用BindingNavigator从数据库中插入/更新/删除数据库中的记录,考虑到我使用的是Entity Framework,我不知道怎么可能。

For example,I tried this to save changes after editing a row, but it didn't work: 例如,我尝试这样做是为了在编辑一行后保存更改,但是没有用:

 private void studentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        UE.SaveChanges();
    }

I know it's an old thread but I faced the same problem with no answer here. 我知道这是一个旧线程,但是在这里我没有答​​案也面临着同样的问题。

this line is breaking DataSource's connection to context: 此行中断了DataSource与上下文的连接:

studentBindingSource.DataSource = UE.Students.ToList();

changed it to: 更改为:

studentBindingSource.DataSource = UE.Students;

but it throws an exception, so I just bind it to local data: 但是会引发异常,因此我将其绑定到本地数据:

studentBindingSource.DataSource = UE.Students.Local;

Also you need to make sure local data has filled before binding. 另外,在绑定之前,您还需要确保已填充本地数据。

Please define "it didn't work". 请定义“无效”。 Is the data at least getting pushed to the underlying entity ? 数据是否至少被推送到基础实体?

I remember there was some issue with those "light weight" toolbar buttons caused by the fact that they don't cause a loss of focus, thus there's no validation happening on the datagrid. 我记得那些“轻量级”工具栏按钮存在一些问题,因为它们不会引起焦点丢失,因此在数据网格上没有进行任何验证。

Just before your call to UE.SaveChanges(), try forcing validation by doing: 在调用UE.SaveChanges()之前,请尝试通过以下方式强制验证:

this.Validate();

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM