gpt4 book ai didi

c# - 如何通过 BindingNavigator 插入、更新和删除 DataGridView 的记录到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:18 24 4
gpt4 key购买 nike

我的数据库中有一个 Student 表和一堆其他表,名为 University,我使用 Entity Framework 在我的 winforms 应用程序中连接到它。 My Entity Framework model

我从 Entity Framework 模型中的 Student 表创建了一个 DataSourceMy Data Source

然后我将 DataSource 拖到我的表单上。(见下图)
我知道如何将 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();
}

My Form

但我想使用 BindingNavigator 从数据库中插入/更新/删除记录,考虑到我使用的是 Entity Framework,我不知道这怎么可能。

例如,我尝试在编辑一行后保存更改,但没有成功:

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

最佳答案

我知道这是一个旧线程,但我遇到了同样的问题,但在这里没有答案。

这一行打破了 DataSource 与上下文的连接:

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

改为:

studentBindingSource.DataSource = UE.Students;

但它抛出异常,所以我只是将它绑定(bind)到本地数据:

studentBindingSource.DataSource = UE.Students.Local;

绑定(bind)前还需要确保本地数据已经填满。

关于c# - 如何通过 BindingNavigator 插入、更新和删除 DataGridView 的记录到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com