Passing a parameter to an event handler

I want to pass my List<string> as a parameter using my event

 public event EventHandler _newFileEventHandler; List<string> _filesList = new List<string>(); public void startListener(string directoryPath) { FileSystemWatcher watcher = new FileSystemWatcher(directoryPath); _filesList = new List<string>(); _timer = new System.Timers.Timer(5000); watcher.Filter = "*.pcap"; watcher.Created += watcher_Created; watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; } void watcher_Created(object sender, FileSystemEventArgs e) { _timer.Elapsed += new ElapsedEventHandler(myEvent); _timer.Enabled = true; _filesList.Add(e.FullPath); _fileToAdd = e.FullPath; } private void myEvent(object sender, ElapsedEventArgs e) { _newFileEventHandler(_filesList, EventArgs.Empty);; } 

and from my main form I want to get this list:

 void listener_newFileEventHandler(object sender, EventArgs e) { } 
+9
c # winforms
Dec 27 '12 at 17:08
source share
2 answers

Create a new EventArgs class, for example:

  public class ListEventArgs : EventArgs { public List<string> Data { get; set; } public ListEventArgs(List<string> data) { Data = data; } } 

And make your event as follows:

  public event EventHandler<ListEventArgs> NewFileAdded; 

Add a shooting method:

 protected void OnNewFileAdded(List<string> data) { var localCopy = NewFileAdded; if (localCopy != null) { localCopy(this, new ListEventArgs(data)); } } 

And when you want to handle this event:

 myObj.NewFileAdded += new EventHandler<ListEventArgs>(myObj_NewFileAdded); 

The handler method will look like this:

 public void myObj_NewFileAdded(object sender, ListEventArgs e) { // Do what you want with e.Data (It is a List of string) } 
+46
Dec 27 '12 at 17:10
source share

You can define the event signature as you like. If the only information you need to provide to the event is this list, then just pass this list:

 public event Action<List<string>> MyEvent; private void Foo() { MyEvent(new List<string>(){"a", "b", "c"}); } 

Then, when subscribing to the event:

 public void MyEventHandler(List<string> list) { //... } 
+2
Dec 27 '12 at 17:17
source share



All Articles