基于我们在VS2010中主要在VB.NET中完成的测试,似乎当你关闭WinForm时,该窗体上DataGridView的“RowValidating”事件的行为会有所不同,具体取决于表单是MODAL还是NON-MODAL。我们所做的是打开表单(MODAL和NONMODAL)并更改单元格的值,然后立即单击“X”以关闭表单。看起来像“RowValidating”事件如果网格在MODAL表单上,则不会触发,但是当网格处于非模式形式时它会触发。我们无法弄清楚为什么......这是.NET中的已知错误吗?
这是我们的测试。您可以通过键入并查看是否从处理程序获取RowValidating弹出窗口来运行在即时窗口中:
_SandboxTest.DataGridViewTestModal
or
_SandboxTest.DataGridViewTestNonModal
这是代码:
Module _SandboxTest
Sub DataGridViewTestNonModal()
Dim frm As New Form
Dim dtable As New DataTable()
dtable.Columns.AddRange({New DataColumn("Column1"), New DataColumn("Column2"), New DataColumn("Column3")})
dtable.Rows.Add({"test", "abc", "def"})
dtable.Rows.Add({"test2", "abc2", "def2"})
Dim dg As New DataGridView
dg.DataSource = dtable
dg.AllowUserToAddRows = False
Try
AddHandler dg.RowValidating, AddressOf RowValidatingHandler
frm.Controls.Add(dg)
frm.Show()
Do
Application.DoEvents()
Loop While frm.Visible
Finally
RemoveHandler dg.RowValidating, AddressOf RowValidatingHandler
End Try
End Sub
Sub DataGridViewTestModal()
Dim frm As New Form
Dim dtable As New DataTable()
dtable.Columns.AddRange({New DataColumn("Column1"), New DataColumn("Column2"), New DataColumn("Column3")})
dtable.Rows.Add({"test", "abc", "def"})
dtable.Rows.Add({"test2", "abc2", "def2"})
Dim dg As New DataGridView
dg.DataSource = dtable
dg.AllowUserToAddRows = False
Try
AddHandler dg.RowValidating, AddressOf RowValidatingHandler
frm.Controls.Add(dg)
frm.ShowDialog()
Finally
RemoveHandler dg.RowValidating, AddressOf RowValidatingHandler
End Try
End Sub
Private Sub RowValidatingHandler(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
MsgBox("RowValidating was fired!")
End Sub
End Module
答案 0 :(得分:1)
我不能告诉你为什么会发生这种情况,但我只是对我们的一个非模态表单进行了测试,当我们关闭它时,RowValidating事件就会触发。
修改强>
我现在可以重现这个问题。使用非模态形式,RowValidating会触发,但是使用模态形式则不会。这很奇怪,我很确定这是一个错误。在窗体关闭之前,您始终可以调用Me.ValidateChildren来强制窗体中的控件进行验证。
答案 1 :(得分:0)
刚刚找到答案: http://msdn.microsoft.com/en-us/library/ms229603.aspx
已在几个网站上发布此问题,因此可以在此处或那里看到任何更改。问题的关键在于它似乎是微软的DataGridView实现的BUG,尽管他们拒绝修复它。
解决此问题的一种方法是触发自己验证onFormClose / OnFormClosing:
Private Sub MyFormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
Dim f = DirectCast(sender, Form)
If f.Modal AndAlso Not f.ValidateChildren Then
e.Cancel = True
End If
End Sub
以下是我发布此问题的链接(用于监控更改):
http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/cd0b6e1a-9453-4092-b764-b93e612dda51
https://connect.microsoft.com/VisualStudio/feedback/details/653413/datagridviews-rowvalidating-event-fires-differently-when-closing-a-modal-v-nonmodal-form#details