Passing parameter to an event handler [stackoverflow],

Source: Internet
Author: User

Passing parameter to an event handler [stackoverflow],

Q:

I want to pass myList<string>As 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){}
A:

Make a new EventArgs class such:

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

And make your event as this:

public event EventHandler<ListEventArgs> NewFileAdded;

Add a firing 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 wowould appear like this:

public void myObj_NewFileAdded(object sender, ListEventArgs e){       // Do what you want with e.Data (It is a List of string)}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.