简体   繁体   English

如何保存dataGridView更改的数据?

[英]How to save dataGridView changed data?

I'm try to create database application and implement MVP pattern . 我正在尝试创建数据库应用程序并实现MVP模式 I'm using EF+CodeFirst. 我正在使用EF + CodeFirst。 There is View , Presenter and Model . ViewPresenterModel

View have dataGridView and SetData() method. 视图具有dataGridViewSetData()方法。

public void SetData(IEnumerable<Goods> items)
{
    dataGridView1.DataSource = items.ToList();
}

Presenter retrieve data from Model and call SetData() of View. 演示者从Model检索数据并调用View的SetData()。

internal void Select()
{
    var data = _modelGoods.Select();
    _view.SetData(data);
}

But, how to save a changed cell data? 但是,如何保存更改后的单元格数据?

If you are working with connected entities, the job is simple, you can load data in context and then bind data to the grid and manipulate data and at last call SaveChanges of the context that you loaded data, to apply changes to database. 如果使用连接的实体,则工作很简单,您可以在上下文中加载数据,然后将数据绑定到网格并操作数据,最后调用加载数据的上下文的SaveChanges ,以将更改应用于数据库。

If you are working with disconnected entities, you should track entity changes. 如果使用断开连接的实体,则应跟踪实体更改。 Some of your entities are added, some of them are changed and some of them are deleted. 您的某些实体已添加,其中一些已更改,其中一些已删除。 And you want to insert those added entities and update those changed entities and delete those deleted entities from context. 您想插入那些添加的实体并更新那些更改的实体,并从上下文中删除那些删除的实体。 To do so you can inherit from a BindigList<T> or an ObservableCOllection<T> or use a BindingSource and listen to list changes events and track changes and store changes in 3 separated lists (added, changed, deleted) and then pass these lists to the server to apply changes. 为此,您可以从BindigList<T>ObservableCOllection<T>继承,也可以使用BindingSource侦听列表更改事件并跟踪更改并将更改存储在3个单独的列表(添加,更改,删除)中,然后传递这些列表到服务器以应用更改。

Sample for Connected Entities: 关联实体示例:

SampleDbContext db;
private void Form1_Load(object sender, EventArgs e)
{
    db = new SampleDbContext();
    db.Products.Load();
    this.productDataGridView.DataSource = db.Products.Local.ToBindingList();
}
private void SaveButton_Click(object sender, EventArgs e)
{
    this.productDataGridView.EndEdit();
    db.SaveChanges();
}

Sample for Disconnected Entities: 断开实体的示例:

I suppose you have tracked changes using BindingSource or BindingList<T> or ObservableCollection<T> or even using DataGridView events or something else. 我想您已经使用BindingSourceBindingList<T>ObservableCollection<T>甚至使用DataGridView事件或其他方法来跟踪更改。 Now you should have added, edited and deleted entities and you can pass them to your server code to apply changes this way: 现在,您应该已经添加,编辑和删除了实体,您可以将它们传递给服务器代码以通过以下方式应用更改:

public void SaveChanges(List<Product> added, List<Product> edited, List<Product> deleted)
{
    using (var db = new SampleDbContext())
    {
        foreach (var entity in deleted)
        {
            if (edited.Contains(entity))
                edited.Remove(entity);

            if (added.Contains(entity))
                added.Remove(entity);
            else
                db.Entry(entity).State = EntityState.Deleted;
        }

        foreach (var entity in added)
        {
            if (edited.Contains(entity))
                edited.Remove(entity);
            db.Entry(entity).State = EntityState.Added;
        }

        foreach (var entity in edited)
            db.Entry(entity).State = EntityState.Modified;

        db.SaveChanges();
    }
}

Typically, to update a record using EF, you read the entity object first, update the property values with the new values, the save it back. 通常,要使用EF更新记录,请先读取实体对象,然后使用新值更新属性值,然后将其保存回来。

Something like this. 这样的事情。

var idOfRecord=12;
using(var yourDbContext=new YourDbContext())
{
  var good=yourDbContext.Goods.FirstOrDefault(s=>s.Id==idOfRecord);
  if(good!=null)
  {
    good.Name = "New name read from UI"; //Updating the Name property value
    yourDbContext.Entry(good).State = EntityState.Modified;
    yourDbContext.SaveChanges();
  }
}

Assuming YourDbContext is the name of your DbContext class. 假设YourDbContextDbContext类的名称。 Update the property/class names as needed to match your use case. 根据需要更新属性/类名称,以匹配您的用例。

I am not a expert of MVP pattern, if based on the examples view know about model, 我不是MVP模式专家,如果根据示例视图了解模型,
then you can use DataGridView.CellEndEdit eventhandler 然后可以使用DataGridView.CellEndEdit事件处理程序

private void dgvtest1_CellEndEdit(Object sender, DataGridViewCellEventArgs e)
{
    if(e.RowIndex < 0)
        return;
    if(e.ColumnIndex < 0)
        return;
    DataGridView dgv = (DataGridView)sender;
    DataGridViewRow row = dgv.Rows(e.RowIndex);
    Good model = row.DataBoundItem as Good
    if(model == null)
        return;
    //Then decide which property was changed and update it
    String boundPropertyName= dgv.Columns(e.ColumnIndex).DataPropertyName;
    if(boundPropertyName.Equals(nameOf(model.SomeProperty)) == true)
    {
        //Update value
        return;
    }
    //.. other columns
}

暂无
暂无

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

相关问题 如何将datagridview中更改的数据保存到数据库? - How to save data changed in datagridview to a database? 如何从文本框在datagridview中添加数据并从datagridview中保存数据 - how to add data in datagridview from textbox & save it from datagridview 如何通过单击按钮将DataGridView中的更改发送到数据库(访问)? - How to send changed in DataGridView data to data base (Access) by clicking button? 将datagridview数据保存到xml - Save datagridview data to xml 当DataGridView中有更改的数据时,如何要求关闭表单进行确认 - How to Require Confirmation on Form Close When there is Changed Data in a DataGridView 我可以在运行时将更改的信息保存在datagridview中吗? - Can I save changed information in datagridview at runtime? 如何保存datagridview的输入? - How to save the input of datagridview? 如何将datagridview批量数据保存到sql数据库,而datagridview数据与图像绑定到c#中的SQL数据库 - how to save datagridview bulk data to sql database while the datagridview data binded with images to SQL database in c# C#如何将文本框中的数据插入到datagridview,然后将datagridview数据保存到数据库中? - C# How to Insert data from text boxes to datagridview and then save the datagridview data into database? 如何在C#中将DataGridView多行数据保存到MySQL数据库中 - How to save DataGridView multiple row data in to MySQL database in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM