views:

162

answers:

5

I have a list like this:

List<Controls> list = new List<Controls>

How to handle adding new position to this list?

When I do:

myObject.myList.Add(new Control());

I would like to do something like this in my object:

myList.AddingEvent+= HandleAddingEvent

And than in my HandleAddingEvent delegate handling adding position to this list. How to handle add new position event? How to have this event available?

+3  A: 

You could inherit from List and add your own handler, something like

using System;
using System.Collections.Generic;

namespace test {
    class Program {

        class MyList<T> : List<T> {

            public event EventHandler OnAdd;

            public void Add(T item) {
                if (null != OnAdd) {
                    OnAdd(this, null);
                }
                base.Add(item);
            }

        }

        static void Main(string[] args) {
            MyList<int> l = new MyList<int>();
            l.OnAdd += new EventHandler(l_OnAdd);
            l.Add(1);
        }

        static void l_OnAdd(object sender, EventArgs e) {
            Console.WriteLine("Element added...");
        }
    }
}

Be aware that you should also re-implement AddRange, declare your own event type if you want to know what has been added and so on, this is just a basic idea...

Paolo Tedesco
Thank you very much
tomaszs
Wouldn't ObservableCollection<T> provide this already?
MattH
A: 

You can't do this with List<T>. However, you can do it with Collection<T>. See Collection<T> Class

John Saunders
+4  A: 

What you need is a class that has events for any type of modification that occurs in the collection. The best class for this is BindingList<T>. It has events for every type of mutation which you can then use to modify your event list.

JaredPar
A: 

You cannot do this with standard collections out of the box - they just don't support change notifications. You could build your own class by inheriting or aggregating a existing collection type or you could use BindingList<T> that implements IBindingList and supports change notifications via the ListChanged event.

Daniel Brückner
+2  A: 

I believe What you're looking for is already part of the API in the ObservableCollection(T) class. Example:

ObservableCollection<int> myList = new ObservableCollection<int>();

myList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
    delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)                    
    {
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            MessageBox.Show("Added value");
        }
    }
);

myList.Add(1);
MattH