naouf
naouf

Reputation: 637

Why is my Event Null?

I am using windows forms C#.

I have main Form and child form. The event is in the child Form and I subscribed to this event in the main Form. The problem is that when I click button1 in child form it does nothing (it should fire the event so textBox1 prints the text) because the event is still null although the main form has already subscribed to the event. Am I doing something wrong? Please help how can I fire the event once button1 is clicked.

Child Form:

public partial class ChildForm : Form
{
    public event EventHandler MyEvent;

    private void button1_Click(object sender, EventArgs e)
    {
        if (myEvent != null)
        {
            MyEvent(this, e);
        }
    }

Main Form:

public partial class MainForm : Form
{
    ChildForm ChildFrm= new ChildForm ();

    ChildFrm.MyEvent += new EventHandler(HandleTheEvent);

    private void button1_Click(object sender, EventArgs e)
    {
        ChildForm childfrm = new ChildForm ();
        childfrm.ShowDialog()
    }

    public void HandleTheEvent(object sender, EventArgs e)
    {
        textBox1.Text = "event is fired";
    }

Upvotes: 0

Views: 490

Answers (2)

Kzryzstof
Kzryzstof

Reputation: 8382

Subscribe to the event right after creating the form :)

private void button1_Click(object sender, EventArgs e)
{
  ChildForm childfrm = new ChildForm();
  childfrm.MyEvent += new EventHandler(HandleTheEvent);
  childfrm.ShowDialog()
}

Upvotes: 1

Mikael Koskinen
Mikael Koskinen

Reputation: 12906

You are adding the event handler to an another instance of ChildForm. Change MainForm's button1_click to look like this:

  private void button1_Click(object sender, EventArgs e)
  {
          ChildFrm.ShowDialog()
  }

And your application should work OK.

Here's the working MainForm.cs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ChildFrm.MyEvent += new EventHandler(HandleTheEvent);
    }

    ChildForm ChildFrm = new ChildForm();

    private void button1_Click(object sender, EventArgs e)
    {
        ChildFrm.ShowDialog();
    }

    public void HandleTheEvent(object sender, EventArgs e)
    {
        textBox1.Text = "event is fired";
    }
}

Upvotes: 5

Related Questions