Export (0) Print
Expand All

BindingList.AddNew Method

Adds a new item to the collection.

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

public T AddNew ()
public T AddNew ()
public function AddNew () : T
Not applicable.

Return Value

The item added to the list.

Exception typeCondition

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. For the complete example, see the BindingList 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 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2015 Microsoft