2015-05-29 75 views
2

我的应用程序中有一个BindingList,我希望能够使用AddingNew事件来确定列表中的项目是否包含即将添加的信息。如果是这样,应该中止添加该项目。如何防止将项目添加到AddingNew事件中的BindingList?

基本上,我在找什么,就像e.Cancel = true;。但它不存在。那么,我们如何防止添加项目之前添加项目?

private void AudioStreams_AddingNew(object sender, AddingNewEventArgs e) 
    { 
     byte[] tempStream = (byte[])e.NewObject; 

     if (tempStream != null) 
     { 
      foreach (var item in AudioStreams) 
      { 
       if (item.AudioStream == tempStream) 
       { 
        e.Cancel = true; // Can't do this but need a way to do it. 
       } 
      } 
     } 
    } 
+0

是其绑定到一个DataGridView或其他一些控制? – Larry

回答

2

BindingList不支持默认情况下。 要实现此功能,必须从BindingLit中派生出来

!请注意,只有在使用“.AddNew()”方法(它会返回创建的对象)时才会引发AddingNew-Event。如果使用“.Add()”,事件不会引发。

愿你可以返回NULL &检查我后来

+0

哦 - 刚才看到你已经使用了NULL;) – Cadburry

0

在这种情况下,我可以逃脱设定e.NewObjectnull

0

这里有一个问题。

如果您在调试器中运行代码,您会注意到e.NewObject始终为空,因此使您的测试完全无用。

MSDN(自2.0版本):

通过处理该事件,程序员可以提供自定义项创建和插入行为,而被迫从的BindingList类派生。

所以当你的处理程序方法被调用时,e.NewObject已经是空的。 这个处理程序的目标是让你创建一个新的对象插入到列表中。

通过MSDN提供的代码片段:

// Create a new part from the text in the two text boxes. 
void listOfParts_AddingNew(object sender, AddingNewEventArgs e) 
{ 
    e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text)); 
} 

没有办法取消的项目中的BindingList从事件增加,因为当AddingNew触发该项目尚未添加到列表,并且当ListChanged被触发时,该操作不能被取消。该操作在AddNew方法结束时可再次取消。

所以,如果你想取消这个操作,你应该做的:

BindingList<byte[]> myList; //Your binding list 

byte[] newItem = myList.AddNew(); 

foreach (var item in AudioStreams) 
{ 
    if (item.AudioStream == newItem) 
    { 
     //We ask the BindingList to remove the last inserted item 
     myList.CancelNew(myList.IndexOf(newItem)); 
    } 
} 

//We validate the last insertion. 
//If last insertion has been cancelled, the call has no effect. 
myList.EndNew(myList.IndexOf(newItem)); 
相关问题