Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any changes were made in DataGridView

In my Windows application there is a DataGridView form that shows data from xml file.

Now I want to check if there any changes in DataGridView to ask user does he\she wants to save current changes that were done in DataGridView to the file.

like image 610
Guardian Avatar asked Jan 23 '26 12:01

Guardian


1 Answers

I would use two events in order to detect any change in the DataGridView. These are CellValueChanged for detecting changes on fields and CurrentCellDirtyStateChanged for detecting changes in CheckBox type columns.

Set a boolean flag = true when either of those events occurs and check the status of this flag when the form is closed or whenever you want to ask the user for saving changes.

Example code

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
like image 77
ɐsɹǝʌ ǝɔıʌ Avatar answered Jan 25 '26 12:01

ɐsɹǝʌ ǝɔıʌ