.net DataGridView.SelectionChanged事件在BindingSource.SuspendBindings()打开时触发
在下面的示例中,我创建了一个对象集合,并将它们绑定到DataGridView。单击该按钮时,I.SuspendBinding,然后删除所有记录,然后.ResumeBinding。当我删除{m_dataSource.RemoveAt(pos)}网格的选定行时,将触发DataGridView1_SelectionChanged事件。为什么会这样?我认为.SuspendBinding()可以阻止任何事件通过网格触发。如果不是,那么.SuspendBinding()有什么意义 塔克斯.net DataGridView.SelectionChanged事件在BindingSource.SuspendBindings()打开时触发,.net,vb.net,bindingsource,.net,Vb.net,Bindingsource,在下面的示例中,我创建了一个对象集合,并将它们绑定到DataGridView。单击该按钮时,I.SuspendBinding,然后删除所有记录,然后.ResumeBinding。当我删除{m_dataSource.RemoveAt(pos)}网格的选定行时,将触发DataGridView1_SelectionChanged事件。为什么会这样?我认为.SuspendBinding()可以阻止任何事件通过网格触发。如果不是,那么.SuspendBinding()有什么意义 塔克斯 Imports S
Imports System.ComponentModel
公开课表格1
Private m_dataSource As New BindingList(Of BusinessObjects.Person)
Private Sub DataGridView1_SelectionChanged(sender As System.Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged
Label1.Text = String.Format("SelectionChanged {0}", Date.Now.ToShortTimeString)
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadData()
End Sub
Private Sub LoadData()
Dim tempPerson As BusinessObjects.Person
tempPerson = New BusinessObjects.Person() With {.PersonID = 1, .FirstName = "a", .LastName = "b"}
m_dataSource.Add(tempPerson)
tempPerson = New BusinessObjects.Person() With {.PersonID = 2, .FirstName = "c", .LastName = "d"}
m_dataSource.Add(tempPerson)
BindingSource1.DataSource = m_dataSource
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
BindingSource1.SuspendBinding()
Dim pos As Int32
For pos = m_dataSource.Count - 1 To 0 Step -1
m_dataSource.RemoveAt(pos)
Next
BindingSource1.ResumeBinding()
End Sub
End Class不会停止在datagridview上触发的事件。它停止数据绑定——即当绑定挂起时,datagridview中的更改不会更新原始数据源
由于SelectionChanged
事件完全独立于数据绑定(即使没有数据绑定源也会激发),因此即使数据绑定已暂停,它也会继续激发
您是否特别希望停止SelectionChanged
事件触发?在这种情况下,您可以暂时解除处理程序的绑定,例如
RemoveHandler DataGridView1.SelectionChanged, AddressOf DataGridView1_SelectionChanged
次要编辑
对我的原始答案稍加更正:既然您在
BindingSource
上调用了SuspendBinding()
,那么更正确的说法是对BindingSource
的更改不会传播到它的数据源。哇,我一直认为SuspendBinding抑制了控件的事件,而不是相反。显然,我需要使用的方法是:BindingSource.RaiseListChangedEvents。谢谢你的指导。