Rediger

Del via


BindingList<T>.AddNew Method

Definition

Adds a new item to the collection.

public:
 T AddNew();
public T AddNew ();
member this.AddNew : unit -> 'T
Public Function AddNew () As T

Returns

T

The item added to the list.

Exceptions

The AllowNew property is set to false.

-or-

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

Examples

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";
    }
}
' Add the new part unless the part number contains
' spaces. In that case cancel the add.
Private Sub button1_Click(ByVal sender As Object, _
    ByVal e As EventArgs) Handles button1.Click

    Dim newPart As Part = listOfParts.AddNew()

    If newPart.PartName.Contains(" ") Then
        MessageBox.Show("Part names cannot contain spaces.")
        listOfParts.CancelNew(listOfParts.IndexOf(newPart))
    Else
        textBox2.Text = randomNumber.Next(9999).ToString()
        textBox1.Text = "Enter part name"
    End If

End Sub

Remarks

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 parameterless 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.

Applies to

See also