The best way to approach this is to use .NET's 'ObservableCollection, and its INotify___ facilities.
Some people really struggle with mastering this, and I recommend you prepare yourself by studying the standard way custom events are defined in .NET: [
^].
Here's an example of a Class that inherits from List<int> ... it's a generic collection of integers ... which implements a custom event:
using System;
using System.Collections.Generic;
namespace Jan_1_2014_CollectionWithNotification
{
public class CustomIntCollection : List<int>
{
public class NewIntAddEventArgs : EventArgs
{
public int intValue { get; set; }
public NewIntAddEventArgs(int theInt) { intValue = theInt; }
}
public event EventHandler<NewIntAddEventArgs> NewIntAdded;
public void Add(int newInt)
{
OnRaiseNewIntAdded(new NewIntAddEventArgs(newInt));
base.Add(newInt);
}
protected virtual void OnRaiseNewIntAdded(NewIntAddEventArgs e)
{
EventHandler<NewIntAddEventArgs> handler = NewIntAdded;
if (handler != null) handler(this, e);
}
}
}
You might test the notification event facility of this class like this:
CustomIntCollection cIntCollection = new CustomIntCollection();
private void SomeForm_Load(object sender, EventArgs e)
{
cIntCollection.NewIntAdded += cIntCollection_NewIntAdded;
}
private void cIntCollection_NewIntAdded(object sender, CustomIntCollection.NewIntAddEventArgs e)
{
Console.WriteLine("the integer added = " + e.intValue.ToString());
}
cIntCollection.Add(100);
cIntCollection.AddRange(new List<int>{1,2,3,4});
The code to create custom Events that follows the MS Guidelines (yes, you could do it other ways), and use them, often seems quite strange to new students of C#, but you'll get used to it, and, I believe, you'll realize that what might appear to be a lot of "extra" work is related to allowing:
1. "safety" in code: preventing side-effects
2. creating structures/methods that can be over-ridden in inheriting classes.
[edit]Edit v3 [Nelek] First code block changed from xml to c# to improve color format and readability[/edit]
[edit]Edit v4 [Nelek] Explanation of changes in edit v3 and this line in request of poster[/edit]