save new record entered from Datagridview into the database

╄→гoц情女王★ 提交于 2019-12-13 04:04:03

问题


Am using a DataSet and a TableAdapter to populate a Datagridview. The Datagridview allows inserting new records at the bottom. Now when I enter values for the new record in the Datagridview, the record is not automatically saved back to the database. Which event do U need to handle or what code do I need to write to get the new record saved back to the databse.

am using C#.


回答1:


Are you calling the Update() method on the TableAdapter? The following code comes from MSDN's discussion on the TableAdapter:

try 
{
    this.Validate();
    this.customersBindingSource.EndEdit();

    this.customersTableAdapter.Update(this.northwindDataSet.Customers);
    MessageBox.Show("Update successful"); 
} 
catch (System.Exception ex) 
{
    MessageBox.Show("Update failed"); 
}

There are various places where you can put this sort of logic - as Davide Piras suggests you could have a Save button on your form or if you want data to be saves as each row is entered you can have your save logic with the RowValidated event handler.




回答2:


you can put somewhere a Save button and when user click that button you call a method like this:

private void UpdateDataSet(DataSet dataSet)
{
    // Check for changes with the HasChanges method first.
    if(!dataSet.HasChanges(DataRowState.Modified)) return;

    // Create temporary DataSet variable and
    // GetChanges for modified rows only.
    DataSet tempDataSet = 
        dataSet.GetChanges(DataRowState.Modified);

    // Check the DataSet for errors.
    if(tempDataSet.HasErrors)
    {
        // Insert code to resolve errors.
    }
    // After fixing errors, update the data source with  
    // the DataAdapter used to create the DataSet.
    adapter.Update(tempDataSet);
}


来源:https://stackoverflow.com/questions/7416323/save-new-record-entered-from-datagridview-into-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!