Access mdiparent label1.text from mdichild

Rotorhead

Newcomer
Joined
Mar 3, 2009
Messages
1
Hi guys,

I have googled all over the place, but only found pretty confusing stuff. I will try to make my question as simple as possible, hoping to get an easy answer which a PHP coder like me can understand :o)

So, here's my layout:

I have a parent form and a child form.

On the parent form, I have a label called label1, with a text "Testing".
Now, I want the child to be able to access the text of the label and get it as a string.

As I have no idea on how to connect the child form to the main (parent) form, I am in kind of trouble here :o)

Would you be so kind to help me on this?


Cheers guys

Chris
 
Chris,

First off, all of your MdiChild forms should be declared globally in the MdiParent form and set to null when the MdiParent loads.

On your parent form, label1 should have the public modifier set. Personally, I try to avoid "Protected", "Protected Internal", and "Internal" unless absolutely necessary.

When calling your child form from the parent, first check that the form is not null, otherwise you are liable to destroy the form that someone is working on. If the form is not null, call "BringToFront()" or "Activate()".

If the child form is null, instantiate and call it.

Example:
Code:
void ShowChild1() {
  if ((frmChild1 == null) || (frmChild1.IsDisposed == true)) {
    frmChild1 = new Child1Form();
    frmChild1.MdiParent = this;
    frmChild1.WindowState = (ActiveMdiChild == null) ? FormWindowState.Maximized : ActiveMdiChild.WindowState;
    frmChild1.Show();
  }
  mifrmChild1.Checked = true;
  if (ActiveControl != frmChild1) {
    frmChild1.BringToFront();
  }
}

Now, your MdiChild form must be created in a way that it knows who its parent is.

Code:
MyMdiForm _parent;

public Child1Form(Form parent) {
  InitializeComponent();
  _parent = (MyMdiForm)parent;
}

void SetParentText(string updateText) {
  _parent.label1.Text = updateText;
}

If you don't like setting the label1 modifier to public, you could always create properties to read and/or write to the label1 control.

Here is how you could modify the MdiParent to have a ReadOnly label1 control without setting label1's modifier to public:
Code:
public string Label1Text { set { label1.Text = value; } }

Does this get you moving along in the right direction?
 
Back
Top