如何:儲存資料前先認可資料繫結控制項上的同處理序編輯

 

發行︰ 2016年4月

編輯資料繫結控制項中的值時,使用者必須巡覽目前的記錄,將更新值認可至控制項所繫結的基礎資料來源。 當您將項目從資料來源視窗拖曳至表單時,您所放置的第一個項目會將程式碼產生至 BindingNavigator 的儲存按鈕 Click 事件。 這個程式碼會呼叫 BindingSourceEndEdit 方法。 因此,只會為第一個加入至表單的 BindingSource 產生 EndEdit 方法的呼叫。

EndEdit 呼叫會認可正在編輯的任何資料繫結控制項中,所有正在處理的變更。 因此,如果資料繫結控制項還有焦點時您按一下 [儲存] 按鈕,則該控制項中所有暫止的編輯都會在實際儲存前先認可 (TableAdapterManager.UpdateAll 方法)。

即使使用者嘗試不認可變更就將資料儲存成儲存程序的一部分,您還是可以設定應用程式自動認可變更。

注意

設計工具只會為第一個放置在表單上的項目,加入 BindingSource.EndEdit 程式碼。 因此,您必須對表單上每一個 BindingSource,加入一行呼叫 EndEdit 方法的程式碼。 您可以手動為每一個 BindingSource 加入一行程式碼以呼叫 EndEdit 方法。 或者,您可以將 EndEditOnAllBindingSources 方法加入至表單,然後在執行儲存前呼叫這個方法。

下列程式碼使用 LINQ (Language-Integrated Query) 查詢,以反覆查看所有 BindingSource 元件,並對表單上的每一個 BindingSource 呼叫 EndEdit 方法。

若要對表單上的所有 BindingSource 元件呼叫 EndEdit

  1. 將下列程式碼加入至內含 BindingSource 元件的表單。

            private void EndEditOnAllBindingSources()
            {
                var BindingSourcesQuery =
                    from Component bindingSources in this.components.Components
                    where bindingSources is BindingSource
                    select bindingSources;
    
                foreach (BindingSource bindingSource in BindingSourcesQuery)
                {
                    bindingSource.EndEdit();
                }
            }
    
        Private Sub EndEditOnAllBindingSources()
            Dim BindingSourcesQuery = From bindingsources In Me.components.Components 
                          Where (TypeOf bindingsources Is Windows.Forms.BindingSource) 
                          Select bindingsources
    
            For Each bindingSource As Windows.Forms.BindingSource In BindingSourcesQuery
                bindingSource.EndEdit()
            Next
        End Sub
    
  2. 加入下列程式碼行並緊接在任何呼叫之前,以儲存表單的資料 (TableAdapterManager.UpdateAll() 方法):

                EndEditOnAllBindingSources();
    
            Me.EndEditOnAllBindingSources()
    

請參閱

階層式更新概觀
TableAdapterManager 概觀
TableAdapter 概觀
BindingSource 元件概觀