简体   繁体   中英

How to access parent form from the child form?

I've tried looking this up and I couldn't find anything that I understood.

But what I'm trying to do is create a class with all my functions in, then call it from the parent form.

And one of these functions contains adding controls to the parent form, but I cannot find out how to do this, can somebody help me please and explain it along the way?

Many thanks, Jarrod

Typically, I'd just add a reference to the parent form in the lower class and initialize it in the constructor. Something like this:

public form MyForm : Form
{
    Foo myFoo;

    public MyForm()
    {
        this.myFoo = new Foo(this);
    }
}

public class Foo
{
    private MyForm parentForm;

    public Foo(MyForm parent)
    {
        parentForm = parent;
    }
}

Then you can reference the parent form and manipulate it how you wish. It also works for static classes, too.

Try this;

In your class use this method to add controls to Parent form

public static void AddControl(Form ParentForm,Control control,Point location)
{
control.Location=location;//This is only to show you
Parent.Controls.Add(control);//how it can be done.You can replace this logic with yours
//but make sure to add this Parent.Controls.Add(control),where control will be the name of        your Control.
}

Then whenever you need to add a control call the function as;

ClassName.AddControl(this,new TextBox(),new Point(10,10));//Change ClassName to your class's name.

Anything else please let me know.

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