Export (0) Print
Expand All

BindingSource.AddNew Method

Adds a new item to the underlying list.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public virtual Object AddNew()

Return Value

Type: System.Object
The Object that was created and added to the list.

Implements

IBindingList.AddNew()

ExceptionCondition
InvalidOperationException

The AllowNew property is set to false.

-or-

A public default constructor could not be found for the current item type.

The AddNew method adds a new item to the underlying list represented by the List property. This method sets up the following series of actions:

  1. The EndEdit method is automatically called to commit any pending edit operations.

  2. The AddingNew event is automatically raised. This event can be programmatically handled to construct the new item. This is accomplished in the event handler by setting the NewObject property of the System.ComponentModel.AddingNewEventArgs parameter to the new item. The new object created in the AddingNew event must be of the same type as the type contained in the list or an exception will occur.

    If the AddingNew event is not handled, and the underlying list is an IBindingList, then the request is passed to the list's IBindingList.AddNew method. If the underlying list is not an IBindingList, the item is automatically created through its public default constructor. In either case, the new item is added to the end of the list.

  3. The new item is added immediately to the internal list unless the data source implements the IEditableObject interface. In this case, the new item is not committed until an explicit call to ICancelAddNew.EndNew is made or until a new list operation is initiated. Before it is committed, the new item can be rolled back by calling CancelEdit, in which case the new item is discarded.

This method raises the ListChanged event.

The following code example uses a BindingSource component to bind a list to a DataGridView control. New items are added to the list by the AddingNew event handler. This code example is part of a larger example provided in How to: Customize Item Addition with the Windows Forms BindingSource.

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;
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Show:
© 2015 Microsoft