2011-09-14 73 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); 
} 
相關問題