• 0

[C#] Need to raise event on Add() method for List<T>


Question

I have a variable declared as List<Panel> and I need to raise an event every time I add a panel to the list and I need to do this in the same class has the variable is declared (just beucase I tried to subclass Collection<T> and overriding InsertItem(), but wasn't able to access variables/methods on the same class ehere the Collection<Panel> would be declared.

Can anyone help me out? How can I raise an event on the Add() method of List<T>?

8 answers to this question

Recommended Posts

  • 0

Because you can't override the Add() method of the Generic List<T> class, trying to add events to it will be useless. What you can do, is create a class which extends the System.Collections.CollectionBase class. The CollectionBase class providers an internal collection, to which you add your own Add(), Remove(), Insert() etc. methods to create a externally-strong collection. With the code below, I am defining my custom collection, with an event which can be fired when a string is added to the collection:

public class StringCollection : CollectionBase
	{
		public delegate void StringCollectionEventHandler(object sender, StringEventArgs e);
		public event StringCollectionEventHandler StringAdded;

		public int Add(string item)
		{
			int index = this.InnerList.Add(item);
			if (StringAdded != null)
			{
				StringAdded(this, new StringEventArgs(item));
			}
			return index;
		}
	}

	public class StringEventArgs {
		private string value = string.Empty;

		internal StringEventArgs(string value)
		{
			this.value = value;
		}

		public string Value { get { return value; } }
	}

I make sure I declare both the collection, and my event arguments that I want the event to carry. What happens here is that when the user attaches an event to my collection, my collection will fire that event, passing through the item that was added:

class Program
	{
		static void Main(string[] args)
		{
			StringCollection collection = new StringCollection();
			collection.StringAdded += new StringCollection.StringCollectionEventHandler(collection_StringAdded);
			collection.Add("This		collection.Add("Is		collection.Add("A		collection.Add("Test		collection.Add("String		Console.ReadKey();
		}

		static void collection_StringAdded(object sender, StringEventArgs e)
		{
			Console.WriteLine(string.Format("'{0}' was added to the collection", e.Value));
		}
	}

  • 0

While searching on how to override the Add() method of List<T>, I found someone suggestion overriding the InsertItem() method of Collection<T>. And it works as I wanted. The only problem I was having, was with delegates and events and how would I call them from a different class. But I managed to do it...

Thanks anyway for your help Antaris! :)

  • 0

I see you've already found a solution, but had you considered using ObservableCollection<T>?

It has a built in CollectionChanged event that might be useful for you. This appears to only exist in .NET 3.0, so if you are still only using 2.0, then it really won't help you. If your use of delegates is sufficient, then ignore this, but I thought it might come in handy.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Yeah, I can see that. I would hope that an xbox branded handheld could bridge the legal gap. Maybe to help get around the legal definitions of the differences between Windows and xbox, they could just make it dual-boot. That would be kind of shame because I'm sure an xbox app could do all the same things, but if you have to totally shutdown windows and start it up in "xbox mode" then perhaps the game studios would be more okay with that...then down the road maybe a hot new update removes the requirement to reboot to change modes :-)
    • You will soon be able to book hotels directly through the PayPal app by David Uzondu PayPal is getting into the hotel booking business, thanks to a new partnership with the booking technology company Selfbook, announced today. The plan will stick a hotel booking section right inside the PayPal app, letting millions of users find and pay for rooms from Selfbook's partner hotels. If you have never heard of the company, Selfbook is a booking and payment platform that is usually integrated into a hotel's website to make the often-annoying reservation process a lot easier. Its tech helps hotels get more people booking right on their own site by offering payment options people actually use, like digital wallets. Now, instead of just living on individual hotel sites, Selfbook's network will be featured in PayPal's Offers tab. For hotels, this gives them a direct line to a huge audience of logged-in users. PayPal also says that this partnership will help bring travel booking "into the age of agentic AI," with the help of Perplexity, the conversational AI-powered search engine. The idea is that you will be able to just chat with an AI about a trip, and when it is time to book, you can pay for your hotel right there in the conversation. Selfbook provides the plumbing to make the booking happen, while PayPal and Venmo will show up as the payment methods. According to the PayPal announcement: To handle the money side of things, Selfbook is moving all of its direct card processing over to PayPal's Enterprise Payments platform. For travelers, this just means more choice at checkout. People booking at a hotel that uses Selfbook will see options to pay with PayPal or Venmo, along with "Buy Now, Pay Later" plans for splitting up the cost of a stay.
    • So a rando with an unknown setup has an issue that I am not having, what is your point? I could easily reply with a reddit commenter complaining about Windows 10, but it would be just as pointless as your link. My experience is my experience. It seems like you are trying to prove something different than what my own eyes see. Others may have issues with 11 and choose not to use it for their own reasons, but you'll never be successful trying to tell me I should be concerned with issues that don't exist on my systems.
  • Recent Achievements

    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
    • Week One Done
      VicByrd earned a badge
      Week One Done
    • Reacting Well
      NeoToad777 earned a badge
      Reacting Well
    • Reacting Well
      eric79XXL earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      470
    2. 2
      +FloatingFatMan
      277
    3. 3
      ATLien_0
      245
    4. 4
      snowy owl
      204
    5. 5
      Edouard
      190
  • Tell a friend

    Love Neowin? Tell a friend!