2011-07-28 67 views
1

在下面的示例中,我創建了一組對象並將它們綁定到一個DataGridView。當按鈕被單擊時,我將.SuspendBinding,然後刪除所有記錄,然後.ResumeBinding。當我刪除{m_dataSource.RemoveAt(pos)} Grid的選定行時,會觸發DataGridView1_SelectionChanged事件。爲什麼是這樣?我會認爲.SuspendBinding()會阻止任何事件觸發到網格。如果不是,那麼.SuspendBinding()有什麼意義?開啓BindingSource.SuspendBindings()時觸發的DataGridView.SelectionChanged事件

Thanx。

Imports System.ComponentModel 

公共類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 

末級

回答

2

SuspendBinding()不會停止射擊的事件上的DataGridView。它停止數據綁定 - 即在綁定掛起時,datagridview中的更改不會更新原始數據源。

由於SelectionChanged事件完全獨立於數據綁定(即使沒有數據綁定源也會觸發),因此即使數據綁定已暫停,它也會繼續激活。

您是否特意尋找停止SelectionChanged事件解僱?在這種情況下,你可以臨時解除綁定處理程序,例如

RemoveHandler DataGridView1.SelectionChanged, AddressOf DataGridView1_SelectionChanged 

小修改

小幅回調到我原來的答覆:因爲你在BindingSource稱爲SuspendBinding(),它會更正確地說,更改BindingSource不會傳播到它的數據源。

+0

哇,我一直認爲SuspendBinding抑制事件的控制,而不是其他的方式。顯然,我需要使用的方法是:BindingSource.RaiseListChangedEvents。感謝指導。 –