Change other form text on event close
I want to change the label text in my MdiParent Form when the child form is closed. but I am getting this error "An unhandled exception of type 'System.NullReferenceException' occurred in yourprogram.exe". This is my code:
private void Employees_FormClosing(object sender, FormClosingEventArgs e)
{
(MdiParent as MainForm).setStatusText = "Ready";
}
I have this code in my MdiParent Form:
public string setStatusText
{
set
{
tsStatus.Text = value;
}
}
I tried it too on Employees_FormClosed Event, but I still get the same error. I just couldn't figure out why this is giving me a null reference when I instantiated the class.
source to share
This code is taken from your comment:
private void addEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
{
Employees emp = new Employees();
emp.MdiParent = this.MdiParent;
emp.Show();
tsStatus.Text = "Adding Employee";
}
When I understand this correctly, your method setStatusText
is in the same class as the method addEmployeeToolStripMenuItem_Click
. This means the line emp.MdiParent = this.MdiParent;
is wrong. This must be emp.MdiParent = this;
because you do not want to establish a parent for your child, you want to establish yourself as the parent of your child.
EDIT:
When you get NullReferenceException
using it as
, it can mean two things. Either your variable, in this case MdiParent
, is equal null
, or your variable is not of the correct type, in this case MainForm
.
source to share