29

I have a a .NET 3.5 windows form which I'd like to embed into another form. Is there a quick way to turn that form into a control?

Thanks

4 Answers 4

51

Change the form to inherit from UserControl instead of Form, then fix any compile errors.

5
  • 1
    Just found this answer while tackling this same issue myself. Awesome how easy that is.
    – Dan Tao
    Commented Feb 9, 2010 at 19:20
  • How would I do this in VB.NET? The form is simply declared as Public Class TimeSheetGrid, with no explicit Inherits.
    – ProfK
    Commented Sep 21, 2012 at 7:05
  • In Visual Studio 2012 (at least) or with the relatively simple forms I've tried, doing just this makes usable code but you can't open the control in the VS designer. No errors, but when you open the designer merely shows you a list of all control elements, similar to how it does for file dialog elements/etc. but you see no control layout. If anyone knows how to fix that, do tell! Commented Jan 6, 2013 at 19:01
  • Nevermind my above comment, I didn't see that there is a huge difference between Control and UserControl! This answer DID say UserControl, but I had used Control and that's why I was having the problem. Commented Jan 6, 2013 at 20:48
  • 2
    @ProfK for anyone else coming to this in the future, in VB.net the inherits statement is in the designer
    – majjam
    Commented Jul 8, 2015 at 14:30
9

There's also a way to embed a form in a control: Here's the code in VB:

Public Shared Sub ShowFormInControl(ByRef ctl As Control, ByRef frm As Form)
    If ctl IsNot Nothing AndAlso frm IsNot Nothing Then
        frm.TopLevel = False
        frm.FormBorderStyle = FormBorderStyle.None
        frm.Dock = DockStyle.Fill
        frm.Visible = True
        ctl.Controls.Add(frm)
    End If
End Sub

I think I acquired this code from another post on SO, but I can't remember where, so sorry if this is your code snippet!

1
  • 1
    I think you'd have to change some things for it to work in C#, otherwise the compiler would be angry...
    – Joey
    Commented Apr 2, 2009 at 20:25
0

I used @Neil Barnwell's solution, with an addition. I manually edited the .vbprog file and changed the form's "SubType" to "UserControl":

<SubType>UserControl</SubType>

This allows the icon in the project explorer to show as a User Control, rather than a form.

-3

Not saying that you should do this now but in the future you can take a look at MEF. Its a framework for (among other things) building composite applications which it sounds like might be what you're trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.