通过


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 窗体 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 事件。

适用于

另请参阅