Reputation: 86
I have a BindingList
in my app and I want to be able to use the AddingNew
event to determine whether a an item inside the list contains information that is about to be added. If it does, the addition of the item should be aborted.
Basically, what I'm looking for, is something like e.Cancel = true;
. But it doesn't exist. So, how can we prevent an item being added before it's added?
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.
}
}
}
}
Upvotes: 2
Views: 1565
Reputation: 4796
There is a problem here.
If you run your code in a debugger, you will notice that e.NewObject
is always null, therefore making your test completely useless.
From MSDN (since version 2.0):
By handling this event, the programmer can provide custom item creation and insertion behavior without being forced to derive from the BindingList class.
So when your handler method is called, e.NewObject
is already null. The goal of this handler is for you to create a new object to be inserted in the list.
The code snippet provided by 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));
}
There is no way to cancel an item add in a BindingList from the events, because when AddingNew
is fired the item has not yet been added to the list, and when ListChanged
is fired, the operation is no more cancellable. The operation becomes cancellable again at the end of the AddNew method.
So if you want to cancel this operation, you should do:
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));
Upvotes: 0
Reputation: 1864
BindingList doesnt support this by default. To Implement this feature you have to derive from the BindingLit
!Consider that the AddingNew-Event gets only raised if you use the ".AddNew()" Method (which returns the created object). The event wont raise if you use ".Add()".
May you can return NULL & check i later
Upvotes: 2