Snarfblam,
Thanks for the reply. I had already blown away the code that I was talking about in my first post, but I went back and created some more. This time, I could get NO response to the event.
I have Form1, which is the main form. It has two buttons -- the first button creates an instance of Class2, and the second button fires the custom event (MyEvent). When the user clicks on the first button, an instance of Class2 is created. In the Class2 constructor, an instance of Class3 is created.
Here is the code for the main form:
namespace EventsTesting
{
public partial class Form1 : Form
{
//Declare a public event
public event EventHandler MyEvent;
//Declare a variable for a Class 2 object
Class2 secondClass;
public Form1()
{
InitializeComponent();
}
//Create Class2 button click event handler
private void btnCreateClass2_Click(object sender, EventArgs e)
{
//Instantiate a new Class2 object
secondClass = new Class2();
}
//Fire event button click event handler
private void btnFireEvent_Click(object sender, EventArgs e)
{
//If there are any subscribers to the event
if (this.MyEvent != null)
{
//Fire the event
this.MyEvent(this, new EventArgs());
}
}
}
}
Here is the code for Class2:
namespace EventsTesting
{
class Class2
{
//Declare a Form1 object
Form1 parentClass;
//Declare a Class3 object
Class3 childClass;
public Class2()
{
//Instantiate the Form1 object
parentClass = new Form1();
//Add an event handler for the Form1 event
parentClass.MyEvent += new EventHandler(parentClass_MyEvent);
//Notify the user that Class2 has been instantiated
MessageBox.Show("Class 2 created!");
//Instantiate the Class3 object
childClass = new Class3();
}
//Parent class' MyEvent event handler
void parentClass_MyEvent(object sender, EventArgs e)
{
//Show a user message
MessageBox.Show("Event consumed in Class 2");
}
}
}
And finally, the code for Class3:
namespace EventsTesting
{
class Class3
{
//Declare a Form1 object
Form1 grandParentClass;
public Class3()
{
//Instantiate the Form1 object
grandParentClass = new Form1();
//Add an event handler for the Form1 MyEvent event
grandParentClass.MyEvent += new EventHandler(grandParentClass_MyEvent);
//Notify the user that the Class3 object is instantiated
MessageBox.Show("Class 3 created!");
}
//Event handler for Form1 MyEvent
void grandParentClass_MyEvent(object sender, EventArgs e)
{
//Show user message
MessageBox.Show("Event consumed in Class 3");
}
}
}
When I fired the event, nothing happened. When I debugged the program, I found that there were no subscribers to the event.
I'm sure this is a very elementary problem, but any help in understanding would be greatly appreciated. Thanks for your time!