cmthakur
cmthakur

Reputation: 2356

How to open a form within a form?

I have a Parent form and i like to open a child form within the the parent form.

Can this be done? If yes please reply me with sample code .

Thanks !

Upvotes: 14

Views: 64826

Answers (7)

Ronjun Cajilig
Ronjun Cajilig

Reputation: 11

var childform = new  form2();
childform.TopLevel=false;
this.Controls.add(childform);
childform.Show();

This works for me.

Upvotes: -1

Eben Roux
Eben Roux

Reputation: 13256

It depends on what you mean by "within the form". If you need to have the child form shown as a control of the parent form I guess you could try ParentForm.Controls.Add(new ChildForm()). Or maybe even place the child form in an existing container in the parent form by again using the containing control's Controls collection.

HTH

Upvotes: 6

BillW
BillW

Reputation: 3435

I note that all the answers here assume the OP intended to use MDI Form architecture, although that's never explicitly stated.

And there is another way a Form can be made a 'Child' of another Form: by simply setting its 'TopLevel property to 'False, and then setting its 'Parent property to the other Form.

Form2 f2 = new Form2();
f2.TopLevel = false;
f2.Parent = someOtherForm;
f2.Show();

By the way I think the whole idea of 'Forms within Forms' is a BAD idea, and MDI Architecture is now, justifiably, deprecated by MS.

Much better, I believe, to make secondary Forms 'Owned, and if you must have other Containers inside a Form, use UserControls, Panels, etc.

Upvotes: 7

jia
jia

Reputation: 21

Form child = new Form();
child.MdiParent = this;
child.Show();

Write these lines of code in parent form and check.

Upvotes: 0

Dulini Atapattu
Dulini Atapattu

Reputation: 2735

Following is the code to do what you want:

Assume that button1 is in the parent form.

private void button1_Click(object sender, EventArgs e)
        {
            this.IsMdiContainer = true;
            Form Form2 = new Form();
            Form2.MdiParent = this;
            Form2.Show();
        }

Also the following link will provide you more better details of what you want to do:

http://www.codeproject.com/KB/cs/mdiformstutorial.aspx

Hope this helps...

Upvotes: 14

Alex Aza
Alex Aza

Reputation: 78487

Modal dialog:

var form = new Form1();
form.Parent = this;
form.ShowDialog();

MDI child:

var newMDIChild = new Form1();
newMDIChild.MdiParent = this;
newMDIChild.Show();

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176956

inform child form that its MdiParent is current form.

MDI:

 form2 frm = new form2 ();
    frm.MdiParent = this;
    frm.Show();

Upvotes: 3

Related Questions