简体   繁体   中英

How to set Access a parent form control From it's child form

I am using windows form Application, all that i have knew have tried, but cannot access Child form Control of a Parent form.

Code that i have tried till now:

this.ParentForm.Controls["PanelContainer"].Visible = false;

and

this.MdiParent.Controls["pnlContainer"].Visible = false;

and

Form myform = btnLogin.FindForm();
myform.Parent.Controls["PanelContainer"].Visible = false;

I have tried setting a public property for the Panel Control:

public Panel PanelContainer
{
    set { pnlContainer = value; }
    get { return pnlContainer; }
}

but all i am getting an exception, "Onject Reference not set to an instance of an object"

EDIT1 : Here is the snapshot of My Form:

在此处输入图片说明

EDIT2 : this is how I am adding the form in ContainerPanel

var login = new Login();
login.TopLevel = false;
login.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
PanelContainer.Controls.Add(login);
login.Show();

If I understand this right, I had the same problem. I was confused by the term "ParentForm" and this other answer really helped explain why I was doing it wrong.

Whats the difference between Parentform and Owner

To allow a top-level form to share a control with a lower-level form:

1.) In form designer, open the main form, select the control to be shared, and set its modifier to "Internal".

2.) When calling the lower-level form, supply "this" as the owner parameter of Show().

LoginForm login = new LoginForm();
login.Show(this);

3.) From the lower-level form, you can now reference the Owner property and cast it back to its class type to access the shared control by name.

((MainForm)Owner).PanelContainer.Visible = false;

The Controls object off a Control is a collection that is accessible by index.

this.ParentForm.Controls[0].Visible. . .

The name you are referencing would be inside something like:

this.ParentForm.Controls[0].Name

make sure that the control in the parent form is set to public. After that, accessing that control is as simple as

ParentForm frmParentForm= (ParentForm)Application.OpenForms["ParentForm"];
frmParentForm.YourControlName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM