共用方式為


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 。 此程式碼範例是《 如何:用 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

適用於

另請參閱