In my current application I have a main form: frmMain with a statusstrip and a label: lblStatus inside that.
I would like to update that label from inside my user controls, which I add to my main form when I click the concerning button:
ucBeheer ucBeheer = new ucBeheer();
splitContainer1.Panel2.Controls.Add(ucBeheer);
From inside my usercontrol when I do an action, I would like to update lblStatus. I have tried adding the following property to my main form:
public string updateStatus
{
get { return lblStatus.Text; }
set { lblStatus.Text = value; }
}
And then accessing the method like this in my user control:
frmMain mainForm = new frmMain();
mainForm.updateStatus = "This is a test";
But that doesn’t work, I know that this is because I am making a new object of my frmMain, but I don’t know how to solve this otherwise?
I have also found the following way, with an Event Handler but I can’t do that because my user control isn’t actually in my mainForm yet, until I add it there with clicking on the button, so I don’t have a reference to it.
So I’m kinda out of ideas, I hope somebody can help me.
Thanks,
Thomas
Edit: So I managed to do it the following way:
frmMain owningForm = (frmMain)this.Parent.Parent.Parent.Parent;
owningForm.updateStatus = "This is a test";
but this.Parent.Parent.Parent.Parent... doesn’t really seem like good coding to me, is there any other way to get the most top parent?
You could add a property like this to your usercontrol, with this you can access the frmMain that the usercontrol resides in.
UPDATE:
If you just want the top most parent you could use something like this:
Or even make an extension method of that: