如何检查是否在DataGridView中进行了任何更改

Gua*_*ian 1 xml vb.net datagridview

在我的Windows应用程序中,有一种DataGridView表单可以显示xml文件中的数据。

现在,我想检查是否有任何更改,DataGridView以询问用户是否要保存DataGridView对文件所做的当前更改。

equ*_*sde 5

我将使用两个事件来检测中的任何变化DataGridView。这些CellValueChanged用于检测字段上的更改以及CurrentCellDirtyStateChanged检测CheckBox类型列中的更改。

flag = true在这些事件中的任何一个发生时设置一个布尔值,并在关闭表单时或您要询问用户保存更改时检查此标志的状态。

范例程式码

Dim DGVhasChanged As Boolean

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    DGVhasChanged = False

    //Do stuff to populate the DataGridView

End Sub

Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged

    DGVhasChanged = True

End Sub    

Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged

    DGVhasChanged = True

End Sub    

//This example check for changes on Form closing but you can check it on any other event (e.g: When a button is clicked)
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

   If DGVhasChanged = True Then           
       Dim response As MsgBoxResult  
       response = MsgBox("Do you want to save the changes?", MsgBoxStyle.YesNo)
       If response = MsgBoxResult.Yes Then
           //Do stuff to save the changes...
           DGVhasChanged= False
       End If
   End If

End Sub
Run Code Online (Sandbox Code Playgroud)