2015-06-22 71 views
-1

我有一個從包含可編輯列的SQL Server數據庫加載的datagridview。我想檢查用戶是否更改了datagridview中的數據,之後我可以將數據保存回數據庫,並且如果用戶沒有更改任何內容,那麼它將不會將數據保存到數據庫。我不想更新原始記錄上的數據,在datagridview發生更改後,它應該將數據插回數據庫。像主人和用戶模板一樣。Datagridview檢查更改並插入記錄

回答

0

DataGridViewCell不會跟蹤更改。如果您需要知道只有一個單元格的值已更改,請使用CellValueChanged事件並在那裏執行您的操作。如果您需要知道哪些細胞已被修改,所以你可以列舉出來,做是必要的,試試這個:

HashSet<DataGridViewCell> changedCells = new HashSet<DataGridViewCell>(); 
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
{ 
    DataGridView dgv = sender as DataGridView; 
    if (!changedCells.Contains(dgv[e.ColumnIndex, e.RowIndex])) 
    { 
     changedCells.Add(dgv[e.ColumnIndex, e.RowIndex]); 
    } 
} 

不要忘了勾的DataGridView的CellValueChanged事件。當您需要更改單元格列表時,請執行以下操作:

foreach (DataGridViewCell cell in changedCells) 
    { 
    // Your work here 
    } 

這僅適用於UI級別。如果你的數據被代碼改變了,你將需要不同的方法。

See here for complete reference

[Nikola Markovinović][2]答案

+0

感謝您的回覆,但實際上我正在尋找的是在插入記錄之前檢查gridview中的任何更改。我有我的GridView中的模板字段進行編輯,但編輯後,我怎麼知道用戶已經改變了任何東西。 – naeemmalik

0

我想你可以使用asp.net網格的OnRowUpdating="GridViewUpdateEventHandler"

+0

在DataGridView是一個WinForms控制,而不是ASP.NET網格控件。 –

相關問題