Insert all data of a datagridview to database at once

前端 未结 7 851
南方客
南方客 2020-12-08 23:55

I have a datagridview which is created by various action and user\'s manipulation of data. I want to insert all the data of the gridview to the database at once, I know I co

7条回答
  •  無奈伤痛
    2020-12-09 00:40

    I think the best way is by using TableAdapters rather than using Commands objects, its Update method sends all changes mades (Updates,Inserts and Deletes) inside a Dataset or DataTable straight TO the database. Usually when using a DataGridView you bind to a BindingSource which lets you interact with a DataSource such as Datatables or Datasets.

    If you work like this, then on your bounded DataGridView you can just do:

    this.customersBindingSource.EndEdit();
    this.myTableAdapter.Update(this.myDataSet.Customers);
    

    The 'customersBindingSource' is the DataSource of the DataGridView.

    The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.

    From: https://msdn.microsoft.com/en-us/library/ms171933.aspx

    So any changes made inside the DatagridView will be reflected on the Database when using the Update method.

    More about TableAdapters: https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

提交回复
热议问题