在我的Windows应用程序中,有一个DataGridView
表单,显示来自xml文件的数据。
现在,我想检查DataGridView
是否有任何更改,以询问用户是否“她想要将DataGridView
中已完成的当前更改保存到文件中。
答案 0 :(得分:4)
我会使用两个事件来检测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
答案 1 :(得分:0)
以下是使用带有304个时区的XML文件的示例。 Button1加载DGV和Button2检查以查看是否有任何更改。
Dim ds As New DataSet
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pathToXMLFile As String = Environment.GetFolderPath( _
Environment.SpecialFolder.Desktop)
pathToXMLFile = IO.Path.Combine(pathToXMLFile, "TimeZones.xml")
dgv1.DataSource = Nothing
ds.Dispose()
ds = New DataSet
ds.ReadXml(pathToXMLFile) 'read the xml
'after loading all rows are 'changed'
'set all rows to not changed
ds.Tables(0).AcceptChanges()
dgv1.DataSource = ds.Tables(0) 'set datagridviews datasource
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim foo As DataTable = ds.Tables(0).GetChanges
If Not IsNothing(foo) AndAlso foo.Rows.Count > 0 Then
'there were changes
Debug.WriteLine(foo.Rows.Count)
'if you are going to continue to edit
ds.Tables(0).AcceptChanges()
End If
End Sub
答案 2 :(得分:0)
1n