BindingSource.AddNew 方法

定義

將新的項目加入基礎清單中。

public:
 virtual System::Object ^ AddNew();
public virtual object AddNew ();
public virtual object? AddNew ();
abstract member AddNew : unit -> obj
override this.AddNew : unit -> obj
Public Overridable Function AddNew () As Object

傳回

已建立並且加入至清單中的 Object

實作

例外狀況

AllowNew 屬性設定為 false

-或-

目前項目類型找不到公用無參數建構函式。

範例

下列程式碼範例會使用 BindingSource 元件將清單系結至 DataGridView 控制項。 事件處理常式會將新專案新增至清單 AddingNew 。 此程式碼範例是How to: Customize Item Addition with the Windows Forms BindingSource中提供的較大範例的一部分。

private:
   
    void OnMainFormLoad(Object^ sender, EventArgs^ e)
    {
        // Add a DemoCustomer to cause a row to be displayed.
        this->customersBindingSource->AddNew();
          
        // Bind the BindingSource to the DataGridView 
        // control's DataSource.
        this->customersDataGridView->DataSource = 
            this->customersBindingSource;
    }
private void Form1_Load(System.Object sender, System.EventArgs e)
{
    // Add a DemoCustomer to cause a row to be displayed.
    this.customersBindingSource.AddNew();

    // Bind the BindingSource to the DataGridView 
    // control's DataSource.
    this.customersDataGridView.DataSource = 
        this.customersBindingSource;
}
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs)

    ' Add a DemoCustomer to cause a row to be displayed.
    Me.customersBindingSource.AddNew()

    ' Bind the BindingSource to the DataGridView 
    ' control's DataSource.
    Me.customersDataGridView.DataSource = Me.customersBindingSource

End Sub

備註

方法 AddNew 會將新專案新增至 屬性所 List 代表的基礎清單。 此方法會設定下列一系列動作:

  1. 系統 EndEdit 會自動呼叫 方法,以認可任何擱置的編輯作業。

  2. 事件 AddingNew 會自動引發。 此事件可以透過程式設計方式處理,以建構新專案。 這會在事件處理常式中完成,方法是將 NewObject 參數的 System.ComponentModel.AddingNewEventArgs 屬性設定為新專案。 在 事件中 AddingNew 建立的新物件必須與清單中所包含的類型相同,否則會發生例外狀況。

    AddingNew如果未處理事件,且基礎清單為 IBindingList ,則會將要求傳遞至清單的 IBindingList.AddNew 方法。 如果基礎清單不是 IBindingList ,則專案會自動透過其公用無參數建構函式建立。 不論是哪一種情況,新專案會新增至清單結尾。

  3. 除非資料來源實 IEditableObject 作 介面,否則新專案會立即新增至內部清單。 在此情況下,除非明確呼叫 ICancelAddNew.EndNew 或起始新的清單作業,否則不會認可新專案。 認可之前,可以呼叫 CancelEdit 來復原新專案,在此情況下會捨棄新專案。

這個方法會 ListChanged 引發 事件。

適用於

另請參閱