Shaiwal Tripathi
Shaiwal Tripathi

Reputation: 627

Unable to access Label text of MDI Parent Form from Child Form

I have the following situation.

I store the username after successfull login in MDI Parent form (in a label) for future use. But when I am trying to access that label text from Child form. It's showing nothing. I exposed the label property in parent form Like this...

public string UserNameText
{
    get
    {
        return this.lblUserName.Text;
    }

    set
    {
        this.lblUserName.Text = value;
    }
}

But when I am trying to access that label text from child form it's showing empty string. Here is the code of child form button click.

private void button1_Click(object sender, EventArgs e)
{            

   frmHome Home = new frmHome();    //frmHome is name of my parent Form.
   MessageBox.Show(Home.UserNameText);
}

Upvotes: 2

Views: 959

Answers (1)

GuidoG
GuidoG

Reputation: 12014

try it like this:

private void button1_Click(object sender, EventArgs e)
{            
   frmHome Home = (frmHome)this.ParentForm;
   MessageBox.Show(Home.UserNameText);
}

Note that this will only work if the MDI Child form has its property MdiParent set correct.

Upvotes: 3

Related Questions