How to synchronize Database and DataGridView

前端 未结 1 1523
Happy的楠姐
Happy的楠姐 2020-12-19 16:52

I have been trying to synchronize a database trough a DataGridView. So far I have created a data model class. This class contains multiple Properties that match

相关标签:
1条回答
  • 2020-12-19 17:26

    You need to use the BindingSource object. This will keep your DataTable synchronized with the DataGridView.

    So set the DataSource of the BindingSource to the table, then set the DataSource of the DataGridView to the BindingSource.

    Example:

    // DataGridView
    DataGridView dg = new DataGridView();
    
    // BindingSource (used for synchronizing table and grid)
    BindingSource bs = new BindingSource();
    
    // Set DataSource of BindingSource to table
    bs.DataSource = table;
    
    // Set grid DataSource
    dg.DataSource = bs;
    

    To update the underlying database you would usually call

    bindingsource.EndEdit();
    dataAdapter.Update(dataTable);
    

    Here's a tutorial and a bit more in-depth info about the binding source object:

    Saving Data from Application to Database (msdn):

    Data Binding using LINQ to SQL in C#

    0 讨论(0)
提交回复
热议问题