Tigraine

Daniel Hoelbling-Inzko talks about programming

Windows Forms: Form within a panel

I already blogged about Visual Inheritance as a tool for avoiding DRY violation.

Once you’re through with any better book on object oriented design you should have found another important oo principle:

Favor object composition over class inheritance

But how to do that in Windows Forms?
Well, if you dig with Reflector into the Form class you’ll discover that it’s derived from Control. And every container in Winforms accepts Control as it’s child objects.

image

Now, this makes it possible to just create a Panel and say:

panel1.Controls.Add(form);

But after running you’ll get a ArgumentException stating that you can’t add a top level control at this level.

The solution to this is even simpler, you simply need to tell the form to not be top level any more:

form.TopLevel = false;

And you’re done, you just need to set the BorderStyle on your form to get rid of the ugly borders and you’ve successfully embedded a form into another form.

The complete example looks like this:

Form1 form = new Form1();
form.TopLevel = false;
panel1.Controls.Add(form);
form.Show();

My Photography business

Projects

dynamic css for .NET

Archives

more