BindingSource.SuspendBindings()打开时触发DataGridView.SelectionChanged事件

时间:2011-07-28 18:17:36

标签: .net vb.net bindingsource

在下面的示例中,我创建了一个对象集合并将它们绑定到DataGridView。单击该按钮时,我.SuspendBinding,然后删除所有记录,然后.ResumeBinding。当我删除网格的选定行的{m_dataSource.RemoveAt(pos)}时,会触发DataGridView1_SelectionChanged事件。为什么是这样?我认为.SuspendBinding()会阻止任何事件触发到网格。如果没有,那么.SuspendBinding()是什么意思?

感谢名单。

Imports System.ComponentModel

Public Class Form1

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

结束班

1 个答案:

答案 0 :(得分:2)

SuspendBinding()不会停止在datagridview上触发事件。它会停止数据绑定 - 即在挂起绑定时,datagridview中的更改不会更新原始数据源。

由于SelectionChanged事件完全独立于数据绑定(即使没有数据绑定源也会触发),即使数据绑定已被暂停,它也会继续触发。

你是否特意想停止SelectionChanged事件发生?在这种情况下,您可以暂时取消绑定处理程序,例如

RemoveHandler DataGridView1.SelectionChanged, AddressOf DataGridView1_SelectionChanged

次要修改

对我的原始答案稍作修正:自从您在SuspendBinding()上调用BindingSource后,对BindingSource的更改不会传播到其数据源更为正确。< / p>