This question already has answers here:
Pass extra parameters to an event handler?
(10 answers)
Closed 9 years ago.
i want to pass my List<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)
{
}
Make a new EventArgs class such as:
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 would appear like this:
public void myObj_NewFileAdded(object sender, ListEventArgs e)
{
// Do what you want with e.Data (It is a List of string)
}
You can define the signature of the event to be whatever you want. If the only information the event needs to provide is that list, then just pass that 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)
{
//...
}
Related
I can't run my code because there is a error saying:
Cannot assign to 'OnNewLand' because it is a 'method group
This is strange because I have used the same structure as my other methods and there were no problem with them.
Here is my code.
private void CreateNewFlight()
{
string flightCode = ReadFlightCode();
//Create the new bidder
if (!string.IsNullOrEmpty(flightCode))
{
FlightWindow frm = new FlightWindow(Flightcode.Text);
frm.Show();
//Subscribe to the publisher's new bid and quit bid events
frm.NewStart += OnNewStartClick;
frm.NewChangeRoute += OnNewChangeRoute;
frm.OnNewLand += OnNewLand; <----Here is the error <-------
}
}
Cannot assign to 'OnNewLand' because it is a 'method group
My other window:
public event EventHandler<Start> NewStart;
public event EventHandler<ChangeRoute> NewChangeRoute;
public event EventHandler<Land> NewLand;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Start startinfo = new Start(this.Title);
OnNewStart(startinfo); //Raise event
btnLand.IsEnabled = true;
Routetxt.IsEnabled = true;
changebtn.IsEnabled = true;
btnStart.IsEnabled = false;
}
private void changebtn_Click(object sender, RoutedEventArgs e)
{
ChangeRoute changeinfo = new ChangeRoute(this.Title, Routetxt.Text);
OnNewChangeRoute(changeinfo); //Raise event
}
private void btnLand_Click(object sender, RoutedEventArgs e)
{
Land landinfo = new Land(this.Title);
OnNewLand(landinfo); //Raise event
}
//Raise Event
public void OnNewStart(Start e)
{
if (NewStart != null)
NewStart(this, e);
}
public void OnNewChangeRoute(ChangeRoute e)
{
if (NewChangeRoute != null)
NewChangeRoute(this, e);
}
public void OnNewLand(Land e)
{
if (NewLand != null)
NewLand(this, e);
}
You need
frm.OnNewLand += NewLand;
instead of
frm.OnNewLand += OnNewLand;
You might be interested to know what does it mean by method group. Visit this so thread.
This question already has answers here:
Passing Parameter to Backgroundworker
(3 answers)
Closed 7 years ago.
I am wanting to pass an additional parameter to my DoWork method, but am getting a compile error of No overload for 'backgroundWorker1_DoWork' matches delegate 'System.ComponentModel.DoWorkEventHandler'
This is my syntax, what should I do to fix this?
namespace Testing
{
public partial class Form1 : Form1
{
public static string[] employeeName;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1WorkerSupportsCancellation = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void btn1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(employeeName);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e, string[] employeeName)
{
//Just for example sake
for (int q = employeeName.GetLowerBound(0); q <= employeeName.GetUpperBound(0); q++)
{
MessageBox.Show(employeeName[q];
}
}
}
}
DoWorkEventHandler has the following definition :
public delegate void DoWorkEventHandler(
Object sender,
DoWorkEventArgs e
)
You cannot add a third argument. The object you want to get is in DoWorkEventArgs.Argument property.
public partial class Form1 : Form1
{
public static string[] employeeName;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1WorkerSupportsCancellation = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void btn1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(employeeName);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string[] employeeName = (string[])e.Argument;
//Just for example sake
for (int q = employeeName.GetLowerBound(0); q <= employeeName.GetUpperBound(0); q++)
{
MessageBox.Show(employeeName[q];
}
}
}
I am using c# Windows Form Application and ftpWebRequest, I am doing a directory listing. I have a listbox that will display folders, by using the event DoubleClick in my listbox, the double clicked folder or item in my listbox will show its content. And now my problem is I don't know how to go back to the previous directory by using back button.
Here is my Code File:
namespace myFTPClass
{
public class myFTP
{
public string user;
public string pass;
public delegate void cThread1(string thread1);
public event EventHandler EH;
public List<string> myDIR = new List<string>();
public void getDirectoryList(string getDirectory)
{
try
{
FtpWebRequest fwr = FtpWebRequest.Create(getDirectory) as FtpWebRequest;
fwr.Credentials = new NetworkCredential(user, pass);
fwr.UseBinary = true;
fwr.UsePassive = true;
fwr.KeepAlive = true;
fwr.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader sr = new StreamReader(fwr.GetResponse().GetResponseStream());
while (!sr.EndOfStream)
{
myDIR.Add(sr.ReadLine());
}
}
catch(Exception we)
{
myDIR.Clear();
string msg = we.Message;
}
}
void myCallBackMethod(IAsyncResult ar)
{
cThread1 myThread = (cThread1)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
myThread.EndInvoke(ar);
if (EH != null) EH(this, null);
}
public void Async_getDirectoryList(string dir)
{
AsyncCallback ac = new AsyncCallback(myCallBackMethod);
cThread1 myThread = new cThread1(getDirectoryList);
myThread.BeginInvoke(dir, ac, null);
}
}
}
And Here is my Form1:
namespace my_ftp_v0._01
{
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string forward = "ftp://127.0.0.1/" + listBox1.SelectedItem.ToString();
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void Form1_Load(object sender, EventArgs e)
{
txt_dir.Text = "ftp://127.0.0.1/";
txt_pass.PasswordChar = '‡';
}
void ftp_EH(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler eh = new EventHandler(ftp_EH);
this.Invoke(eh, new object[] { sender, e });
return;
}
for (int i = 0; i < ftp.myDIR.Count; i++)
{
listBox1.Items.Add(ftp.myDIR[i]);
}
}
void btn_connect_Click(object sender, EventArgs e)
{
ftp.Async_getDirectoryList(txt_dir.Text);
ftp.user = txt_user.Text;
ftp.pass = txt_pass.Text;
}
}
}
Move your SetDirectoryList to its own method
Add a Stack object to your class to track your requests
When the user double clicks add the request to the stack and then set the directory.
When the user hits the back
button, check if the stack has a request, if it does, pop it off and
call the set directory method.
Something like this...
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
Stack _requestStack = new Stack();//Stack to store requests
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
if(_requestStack.Count > 0)
{
string directoryPath = (string)_requestStack.Pop();
SetDirectoryList(directoryPath);
}
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string directoryPath = listBox1.SelectedItem.ToString();
_stack.Push(directoryPath);
SetDirectoryList(directoryPath);
}
void SetDirectoryList(string directoryPath)
{
string forward = "ftp://127.0.0.1/" + directoryPath;
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void btn_back_Click(object sender, EventArgs e)
{
create.server = create.server.TrimEnd('/');
create.server = create.server.Remove(create.server.LastIndexOf('/')+1);
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList("");
}
I've already done this code to my back button and it works properly.
Any way to make this working code simpler ie the delegate { }?
public partial class Form1 : Form
{
private CodeDevice codeDevice;
public Form1()
{
InitializeComponent();
codeDevice = new CodeDevice();
//subscribe to CodeDevice.ConnectionSuccessEvent and call Form1.SetupDeviceForConnectionSuccessSate when it fires
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
}
private void SetupDeviceForConnectionSuccessState(object sender, EventArgs args)
{
MessageBox.Show("It worked");
}
private void button1_Click(object sender, EventArgs e)
{
codeDevice.test();
}
}
public class CodeDevice
{
public event EventHandler ConnectionSuccessEvent = delegate { };
public void ConnectionSuccess()
{
ConnectionSuccessEvent(this, new EventArgs());
}
public void test()
{
System.Threading.Thread.Sleep(1000);
ConnectionSuccess();
}
}
WinForm event subscription to another class
How to subscribe to other class' events in c#?
If don't think you could simplyfy:
public event EventHandler ConnectionSuccessEvent = delegate { }
even in c#3 + you could only do
public event EventHandler ConnectionSuccessEvent = () => { }
However you could simplify
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
to
codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;
public partial class Form1 : Form
{
private EventThrower _Thrower;
public Form1()
{
InitializeComponent();
}
private void DoSomething()
{
MessageBox.Show("It worked");
}
private void button1_Click(object sender, EventArgs e)
{
_Thrower = new EventThrower();
//using lambda expression..need to use .NET2 so can't use this.
_Thrower.ThrowEvent += (sender2, args) => { DoSomething(); };
var eventThrower = new EventThrower();
eventThrower.test();
}
}
public class EventThrower
{
public delegate void EventHandler(object sender, EventArgs args);
public event EventHandler ThrowEvent = delegate { };
public void SomethingHappened()
{
ThrowEvent(this, new EventArgs());
}
public void test()
{
System.Threading.Thread.Sleep(1000);
SomethingHappened();
}
}
I'm trying to get my winform UI to subscribe to an event in EventThrower class. DoSomething never fires.
How to subscribe to other class' events in c#?
The event is not static, one instance of the EventHandler exists for each instance of EventThrower.
You subscribe to the event on _Thrower, yet you create a new instance of EventThrower and call test() on that instance. You never subscribed to the event on that instance, so your handler doesn't run.
It should be:
_Thrower.ThrowEvent += (sender2, args) => { DoSomething(); };
_Thrower.test();
This is because you create a new EventThrower before calling test.
If you change:
var eventThrower = new EventThrower();
eventThrower.test();
to:
_Thrower.test();
It will call DoSomething.