• 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

    • How to change folder colors in OneDrive by Taras Buria Microsoft's OneDrive cloud storage has plenty of useful productivity features that help you get around your file libraries. Colored folders are a relatively new feature that not every OneDrive user is aware of. While the ability to have colorful folders might seem minor at first glance, it can be very helpful for sorting stuff in your OneDrive. Microsoft says the feature lets users "personalize and manage folder colors for better content visibility." Even Apple agrees with this—iOS, iPadOS, and macOS 26 let you change folder colors in the Files/Finder app. Change folder color in OneDrive on Windows The process is very simple, but it is not the same as changing a folder icon in File Explorer. While you can change the icon of any folder in OneDrive on Windows 11 (Right Click > Properties > Customize > Change Icon), these icons do not sync across platforms. At the same time, while OneDrive folder colors do sync, the feature is not available for personal accounts in the web version of OneDrive. As for mobile devices, it is coming soon to Android and iOS OneDrive clients. Despite the current limitations, here is how to change folder colors in OneDrive on Windows: Make sure OneDrive is set up and running and sync is not paused. Find the folder whose color you want to change, and right-click it. Select OneDrive > Folder Color. Pick one of the 16 colors available and click Ok. The OneDrive app will sync your changes so that they appear across all devices that support folder colors in OneDrive. If you have a business account, you can open OneDrive for the web, right-click any folder and select Folder Color. Changes will sync across your devices right away. Do you find colored folders in OneDrive useful? Share your thoughts in the comments.
    • Awesome. That's what I was thinking Jim. Yea from what I can tell you connect the AIC card to the AIC header on the motherboard, so it doesn't just run through the PCI lanes. That's fine guys. Thanks for clarifying 🙂 I was getting a little bit lost with all of this, but I need a minimum of TB3 and the connector on the MB has it, but not on the back of my PC chassis / MB IO shield. Anyway I found that the cheapest I can get it is Amazon at 70 quid, so I'm just gonna have to fork out for it. Thanks everyone. 🙂 👍  Don't worry about Mindovermaster. He's just his chirpy cheerful self lol. Thanks everyone 🙂
    • I wonder why you say that. As we speak, I'm using it to slash off several minutes of my life.
    • I think you may need to adjust your style of approach. I know you won't though. While some were affected by performance issues, and it's not a huge gap... you're acting as if Ryzen couldn't handle 11 at all. Performance issues are purely based on some facts in certain scenarios, while others are not. I see one link with a handful of people discussing the topic. I didn't join those topics or seek them out myself, as I didn't encounter noticeable drops in performance going from 10 to 11. When 10 came out, during that beta testing phase... I was able to continually crash my system simply by renaming files. It might also have to be because I don't have my nose stuck up the butt of single digit percentage points. I don't benchmark my PC every time something new comes out. Single percentage point differences in performance only ruffle the feathers of those that don't care about daily use. If you have a race car, do you compare that to your daily driver? Do you expect your Honda Accord to break the 9 second quarter mile like your 1000HP Pontiac Firebird? If you're so worried about FPS instead of enjoying your games... perhaps opening a curtain in your basement might provide a new perspective in life.
    • Currently updating my Win10 IoT Enterprise LTSC 2021 in a VM (QEMU/KVM) on Linux. but damn, updates take forever (makes me appreciate the lightness on Linux all the more). to give you a general idea... this update finished at 37 minutes into system uptime and I would estimate updates have been running roughly 20-30 minutes (some of this would be download time, but even subtracting that I would guess that 20-30min is close). granted, I only got two cores of my four core CPU (i5-3550) dedicated to the VM. but still, Linux wipes the floor with Windows in this regard. plus, that does not count the reboot which takes even more time.
  • Recent Achievements

    • Reacting Well
      rshit earned a badge
      Reacting Well
    • Reacting Well
      Alan- earned a badge
      Reacting Well
    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      535
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      211
    4. 4
      +Edouard
      204
    5. 5
      snowy owl
      140
  • Tell a friend

    Love Neowin? Tell a friend!