save new record entered from Datagridview into the database
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#.
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);
}
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.
精彩评论