Skip to main content
 首页 » 编程设计

c#之使用 LINQ2SQL (Winforms) 在 DataGridView 编辑后提交更改

2024年02月24日16luoye11

给定一个具有如下 BindingSource 设置的 DataGridView:

在 winform 上,我们使用设计器添加一个名为 myBindingScource 的 BindingSource 对象。 然后在 Form.Designer.cs 上,我们将其添加到 InitializeComponents()

myBindingSource.DataSource = typeof(MyLinq.Person); //Mylinq is the autogenerated Linq Model/Diagram 

稍后,我们在表单本身中执行:

myDataView.DataSource = myBindingSource; 

然后我们有一个填充网格的方法......

using ( myDataContext mdc = new MyDataContext() ) 
{ 
    myDataView.DataSource = from per in mdc.person 
                            select per; 
} 

顺便说一句,我已经在设计时设置了列,一切都显示正常。 由于 LINQ 2 SQL 不返回匿名,“myDataView”是可编辑的,问题来了……

问题是:我如何持久化这些更改?

datagrid中有几十个事件,我不确定哪个更合适。即使我尝试其中一个事件,我仍然不知道我需要执行什么代码才能将这些更改发送回数据库以保留更改。

我记得在 ADO.NET 数据集时代,你会做 dataadapter.Update(dataset);

再假设 retrieve 和 persist() 都在业务层上,方法签名如下所示:

public void LoadMyDataGrid(DataGridView grid); 

该方法获取表单的网格并使用上面显示的 LINQ2SQL 查询填充它。

现在我想创建一个这样的方法:

public void SaveMyDataGrid(DataGridView grid); // or similar 

思路是这个方法不在同一个类(窗体)上,很多例子倾向于假设一切都在一起。

请您参考如下方法:

RowValidated 事件是检查是否需要将更改持久保存到数据库的好地方。

    this.dataGridView1.RowValidated += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowValidated); 
 
    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e) 
    { 
        MyLinq.Person person = dataGridView1.Rows[e.RowIndex].DataBoundItem as MyLinq.Person; 
 
        if (person != null) 
        { 
            // save this person back to data access layer 
        } 
    } 

编辑后:

我不会将数据网格实例传回您的服务层。我会传回IEnumerable<MyLinq.Person>或 IList<MyLinq.Person>然后根据执行的逻辑迭代服务层中的集合;将更改保存到数据访问层(您的数据库)