如何通过BindingNavigator将DataGridView的记录插入,更新和删除DataBase [英] How to insert, update and delete records of a DataGridView to DataBase via BindingNavigator
问题描述
我有一个学生
表和我的数据库中的一些其他表,名为大学
,我使用了实体框架在我的winforms应用程序中连接到它。
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.
我从我的Entity Framework模型中的 Student
表创建了一个 DataSource
。
I created a DataSource
from the Student
table inside my Entity Framework model.
然后我将 DataSource
拖到我的表单上(见下面的图片)
我知道如何填充学生的记录
表(这里只是我的DB中的一个记录)到 DataGridView
中,使用这段代码没有问题:
then I dragged the DataSource
on to my form.(See the pic below)
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:
//An instance of my EFModel
Oublic UniversityEntities UE = new UniversityEntities();
private void Form1_Load_1(object sender, EventArgs e)
{
studentBindingSource.DataSource = UE.Students.ToList();
}
但是我想使用 BindingNavigator
插入/更新/从数据库中删除记录,我不知道如何可能,考虑到我使用实体框架。
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.
例如,我尝试保存更改后编辑一行,但它没有工作:
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.
这一行打破了DataSource与上下文的连接:
this line is breaking DataSource's connection to context:
studentBindingSource.DataSource = UE.Students.ToList();
将其更改为:
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.
这篇关于如何通过BindingNavigator将DataGridView的记录插入,更新和删除DataBase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!