BindingList<T>.AddNew 方法
定义
将新项添加到集合。Adds a new item to the collection.
public:
T AddNew();
public T AddNew ();
member this.AddNew : unit -> 'T
Public Function AddNew () As T
返回
- T
添加到列表的项。The item added to the list.
例外
将 AllowNew 属性设置为 false。The AllowNew property is set to false.
- 或 --or- 未能找到当前项目类型的公共无参数构造函数。A public parameterless constructor could not be found for the current item type.
示例
下面的代码示例演示如何使用 AddNew 方法。The following code example demonstrates how to use the AddNew method. BindingList<T>.BindingList<T>. 有关完整的示例,请参阅 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
注解
AddNew方法将一个新项添加到由属性表示的集合中 Items 。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:
AddingNew自动引发事件。The AddingNew event is automatically raised.
可以通过编程方式处理此事件以构造新的自定义项。This event can be programmatically handled to construct a new custom item. 在事件处理程序中,通过将参数的 NewObject 属性设置 AddingNewEventArgs 为新项来完成此操作。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.
跟踪新项的位置,但在满足以下条件之一之前,不会将其添加到列表中:The position of the new item is tracked, but it is not added to the list until one of the following conditions are met:
相反,在 CancelNew 提交项之前调用方法将导致新项被丢弃。In contrast, calling the CancelNew method before the item is committed will cause the new item to be discarded.
ListChanged提交新项时,此方法会引发事件。This method raises the ListChanged event when the new item is committed.