BindingList<T>.AddNew Method

Adds a new item to the collection.

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)

public T AddNew()

Return Value

Type: T
The item added to the list.

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 collection represented by the Items property. To add a new item, the following logic is used:

  1. The AddingNew event is automatically raised.

    This event can be programmatically handled to construct a new custom item. This is accomplished in the event handler by setting the NewObject property of the AddingNewEventArgs parameter to the new item.

    Otherwise, the new item is automatically created through its public default constructor.

  2. The position of the new item is tracked, but it is not added to the list until one of the following conditions are met:

    • The item is explicitly committed by a call to EndNew.

    • The item is implicitly committed by some other operation that changed the contents of the list, such as an insertion or removal of an item.

In contrast, calling the CancelNew method before the item is committed will cause the new item to be discarded.

This method raises the ListChanged event when the new item is committed.

The following code example demonstrates how to use the AddNew method. BindingList<T>. For the complete example, see the BindingList<T> class overview topic.

// Add the new part unless the part number contains 
// spaces. In that case cancel the add. 
private void button1_Click(object sender, EventArgs e)
{
    Part newPart = listOfParts.AddNew();

    if (newPart.PartName.Contains(" "))
    {
        MessageBox.Show("Part names cannot contain spaces.");
        listOfParts.CancelNew(listOfParts.IndexOf(newPart));
    }
    else
    {
        textBox2.Text = randomNumber.Next(9999).ToString();
        textBox1.Text = "Enter part name";
    }
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft