I have
class A
{
B b;
//call this Method when b.Button_click or b.someMethod is launched
private void MyMethod()
{
}
??
}
Class B
{
//here i.e. a button is pressed and in Class A
//i want to call also MyMethod() in Class A after the button is pressed
private void Button_Click(object o, EventArgs s)
{
SomeMethod();
}
public void SomeMethod()
{
}
??
}
Class A has a instance of Class B.
How can this be done?
The EventArgs class is the base type for all event data classes. EventArgs is also the class you use when an event doesn't have any data associated with it.
To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.
An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.
You'll need to declare a public event on class 'B' - and have class 'A' subscribe to it:
Something like this:
class B
{
//A public event for listeners to subscribe to
public event EventHandler SomethingHappened;
private void Button_Click(object o, EventArgs s)
{
//Fire the event - notifying all subscribers
if(SomethingHappened != null)
SomethingHappened(this, null);
}
....
class A
{
//Where B is used - subscribe to it's public event
public A()
{
B objectToSubscribeTo = new B();
objectToSubscribeTo.SomethingHappened += HandleSomethingHappening;
}
public void HandleSomethingHappening(object sender, EventArgs e)
{
//Do something here
}
....
You need three things (which is marked by comments in code):
Code:
class A
{
B b;
public A(B b)
{
this.b = b;
// subscribe to event
b.SomethingHappened += MyMethod;
}
private void MyMethod() { }
}
class B
{
// declare event
public event Action SomethingHappened;
private void Button_Click(object o, EventArgs s)
{
// raise event
if (SomethingHappened != null)
SomethingHappened();
SomeMethod();
}
public void SomeMethod() { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With