2011-09-14 140 views
0

正在使用DataSet和TableAdapter填充Datagridview。 Datagridview允许在底部插入新记录。现在,当我在Datagridview中输入新记录的值时,记录不会自动保存回数据库。您需要处理哪个事件或需要编写哪些代码才能将新记录保存回数据库。将从Datagridview输入的新记录保存到数据库中

正在使用C#。

+0

您是否使用代码填充gridview(如果是的话请将其发布)或使用DataSource? – Carsten

+0

Windows窗体或Web窗体?你可以显示你用来将数据绑定到网格的代码吗? –

+0

我用TableAdapter及其窗口窗体应用程序填充DataGridView。 – Gonzalez

回答

0

你叫上TableAdapterUpdate()方法?下面的代码来自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"); 
} 

有,你可以把这种逻辑的各个地方 - 如达维德Piras酒店暗示你可能对你的形式,或者如果你想要的数据是一个Save按钮保存为每行输入你可以使用RowValidated事件处理程序保存你的逻辑。

1

,你可以把一个地方保存按钮,当用户点击该按钮调用这样的方法:

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); 
} 
相关问题