代码之家  ›  专栏  ›  技术社区  ›  Martin Marconcini

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

  •  1
  • Martin Marconcini  · 技术社区  · 16 年前

    给定具有如下BindingSource集的DataGridView:

    然后在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;
    }
    

    顺便说一句,我在设计时设置了这些列,一切都正常。 因为LINQ2SQL没有返回匿名,所以“myDataView”是可编辑的,问题来了

    问题是: 如何保持这些更改?

    我记得在ADO.NET数据集时代,您会执行dataadapter.Update(DataSet);

    public void LoadMyDataGrid(DataGridView grid);
    

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

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

    其思想是,该方法不在同一类(形式)上,许多示例倾向于假设所有内容都在一起。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Michael G    16 年前

    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
            }
        }
    

    编辑后:

    我不会将datagrid实例传递回您的服务层。我会回去的 IEnumerable<MyLinq.Person> IList<MyLinq.Person> 然后迭代服务层中的集合,具体取决于执行的逻辑;将更改持久化到数据访问层(数据库)

        2
  •  1
  •   cloggins    16 年前

    DataContext对象上的“save”方法为 SubmitChanges() .

    using (MyContext c = new MyContext())
    {
         var q = (from p in c.People
                 where p.Id == 1
                 select p).First();
         q.FirstName = "Mark";
         c.SubmitChanges();
    }
    

    推荐文章