Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  Windows Development  »  Use Visual Inheritance to Create Consistent Windows Forms in VB.NET and C#
Use Visual Inheritance to Create Consistent Windows Forms in VB.NET and C#
by Monty Nail | Published  04/21/2002 | Windows Development | Rating:
Monty Nail

Monty Nail is a Senior Software Developer for Timeline, Inc. (www.timeline.com) based in Bellevue, Washington. He is responsible for the company's financial reporting product.

Monty is a self-taught programmer with a B.S. in History from Portland State University and has done post-baccalaureate studies in Japanese and TESOL (Teaching English to Speakers of Other Languages).

His first full-time programming job was using VBA to write Excel-based tracking programs for a construction company's cost control department. He has been using Visual Basic since version 4 was released.

 

View all articles by Monty Nail...
Use Visual Inheritance to Create Consistent Windows Forms in VB.NET and C#

Article source code (both VB.NET and C#): visual_inherit.zip

Visual Inheritance is Microsoft's way to describe implementation inheritance of a visual object such as Windows Forms. This may sound complex if you are just moving from VB6, but the concept is similar to using an ActiveX control on a VB6 form. The difference is reusability at the form level.

Inheriting forms is a powerful feature that allows cross-project standardization of common elements on a form that may be changed in one place rather than in countless individual forms. For example, I once had to re-order the buttons on several dozen forms so the buttons flowed left to right as Help, OK, and Cancel instead of OK, Cancel, and Help. If I had used a base Windows Form, I could have changed the order on the base form, re-compiled, and been done with it.

In the following example you will create a form, add controls, save the form in a class library, and inherit that form in another project. VB.NET is shown here but the steps are similar if using C#. You will find both VB.NET and C# implementation in the article code.

Getting Started

In Visual Studio .NET, go to the main menu and select File > New > Blank Solution. Name it VisualInheritanceExample, and click OK.

Create the Base Project

Go to File > Add Project > New Project and select a Windows Application project. Name it StandardCompanyForms, and click OK. Go to View > Solution Explorer and select the Form1.vb. Right-mouse click and select Rename. Change the name to OKCancelForm.vb. Note that this is the name of the file not of the form itself. The properties you set in the form (except for the Name property) will be the defaults when you inherit the form.

Select the form in the design editor, go to View > Properties Window, and make changes so you have the following properties:

PropertyValue
NameformOKCancel
TextStandard Company Form
StartUp PositionCenterScreen

Go to View > Toolbox to show the available controls. Drag and drop a panel control onto the form. The panel control acts as a container for other controls. It is similar to the GroupBox control but does not have a caption. One great feature of a panel is the AutoScroll property that allows scroll bars to appear if the panel contains more controls than can be seen all at once. You won't use that feature in this example but it is something to keep in mind.

By setting the Dock property of the panel to the bottom of the form, the controls you add will always stay at the bottom even after resizing the form. More on this later.

PropertyValue
NamepanelStandardButtons
DockBottom
Size-Height50

Drag and drop three buttons onto the panel control you added so the panel will act as their container. Setting the Anchor property makes the buttons maintain a consistent relative location during form resizing.

PropertyValue
NamebuttonOK
TextOK
Location130, 10
AnchorBottom, Right
PropertyValue
NamebuttonCancel
TextCancel
Location211, 10
AnchorBottom, Right
PropertyValue
NamebuttonAbout
TextAbout
Location5, 10
AnchorBottom, Right

Add Button Event Code

Double-click on buttonOK to generate the click event in the code editor, and add code to close the form when the OK button is clicked.

Private Sub buttonOK_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles buttonOK.Click
    Me.Close()
End Sub

To add a click event for while still in the code editor, click the Class Name dropdown and select buttonCancel from the list. The Method Name dropdown fills with available events. Select Click from the list.

Add code to prompt the users if they really wanted to cancel. A message box with a Yes button and a No button will appear. If the user clicks No, then nothing happens. If the user clicks Yes, then the form is closed.

Private Sub buttonCancel_Click(ByVal sender As Object_
    ByVal e As System.EventArgsHandles buttonCancel.Click
    Dim result As DialogResult
    result = MessageBox.Show("Are you sure you want to cancel?"_
        "Standard Company Caption"MessageBoxButtons.YesNo_
        MessageBoxIcon.Question)
    If result = DialogResult.Yes Then
        Me.Close()
    End If
End Sub

If you want to associate the user hitting the Escape key with buttonCancel, go to the design editor, select the form, and change the CancelButton property to buttonCancel.

Now create a click event for buttonAbout to show some information about the base program. This gives you a starting point for returning information about your program. A word of warning though, you will receive a security error at runtime if executing on a different machine across a network. The StringBuilder class provides highly optimized string concatenation.

Private Sub buttonAbout_Click(ByVal sender As Object_
    ByVal e As System.EventArgsHandles buttonAbout.Click
    Dim objVersionInfo As FileVersionInfo = FileVersionInfo.GetVersionInfo_
        System.Reflection.Assembly.GetExecutingAssembly().Location)
    Dim objStringBuilder As System.Text.StringBuilder = New _
        System.Text.StringBuilder(objVersionInfo.InternalName)
    objStringBuilder.Append(Environment.NewLine)
    objStringBuilder.Append(objVersionInfo.ProductVersion)
    MessageBox.Show(objStringBuilder.ToString(), _
        "Standard Company Caption"MessageBoxButtons.OK_
        MessageBoxIcon.Information)
End Sub

Go to the Solution Explorer and select the StandardCompanyForms project. Right-mouse click and select "Properties" to make the Property Pages UI appear. Note that the Properties item does not appear on the Project menu unless the project item itself is selected. Change the selected item in the startup object dropdown to be formOKCancel, and click OK. You need to do this because you changed the name of the default form.

Go to Debug > Start to run the project, and see how it works. Maximize the form and observe the button locations. Click on each of the buttons.

You are now ready to change the Windows Application project to a Class Library. You could have started this project as a class library but then you would not have been able to run the form until you inherited it.

Select the project StandardCompanyForms in the Solution Explorer, and then select Project > Properties from the main window. On the General property page change the output type from Windows Application to Class Library, and click OK.

Rebuild (recompile) your project. This step is very important. When the project is rebuilt the code is output in a DLL instead of an EXE. If you don't do this step you will not be able to inherit the form in another project.

Create the Deriving Project

On the main menu select File > Add Project > New Project. Choose Windows Application and name it CustomForms. This is the project that will include derived (inherited) forms.

In the Solution Explorer, select the default Form1.vb that was created and delete it. Select the CustomForms project in the Solution Explorer, and right-mouse click to display the shortcut menu. Select Add > Add Inherited Form. The Add New Item UI will appear. Change the name of the form to be created to formInheritedCompanyStandard, then click OK.

The Inheritance Picker UI appears and displays the available components to inherit. Since there is only one, click OK. This adds a reference in the new project to the StandardCompanyForms class library, and creates a form identical to the one in the class library. The controls on the form have small arrows in the upper left hand corner indicating that they are inherited. Hover the mouse over a control to see a tooltip such as "Inherited control (Private)". If you had changed the Modifiers property in the original control, to Protected or Public you would be able to change its properties, such as size, in the inherited form (though you would not be able to delete it).

Select the CustomForms project in the Solution Explorer, and right-click to display the shortcut menu. Select "Set as Startup Project". The project name should now be in bold font.

If you run the code without going to the Project Properties and changing the startup form, you will receive an error. The Task List will show "'Sub Main' was not found in 'CustomForms.Form1'". Double-click the item in the Task List to bring up the Startup Object UI. Select CustomForms.formInheritedCompanyStandard and click OK. Run the code. The form should appear and behave as it did previously.

You are now ready to add your own controls to the form. If you make changes to the base formOKCancel, you will need to recompile that project before your changes will appear in the inherited forms

A Word of Warning

You should carefully plan the content and behavior of your base form before inheriting from it. You need to leave enough room to contain all possible controls that you may add later. You are not able to overlap controls in the inherited form so using a panel control docked to the bottom means that no additional controls can be placed on the bottom of the inherited form.

To demonstrate the reason to use a panel control, add a new button on the base form (formOKCancel) just above the panel control. Set the Anchor property to Bottom. Rebuild the project. Resize the inherited form (formInheritedCompanyStandard) in the design editor so its height is doubled.

Go back to the base form and move the new button a few pixels to the left. Rebuild the project. When you return to the inherited form the new button is at the pixel location not the relative location that you might have expected. Resize the form and see that the offsets are assumed to be from this pixel location.

Summary

Visual inheritance can be a powerful means of reuse allowing you to make design and code changes in one location and have it apply across multiple forms. But, as with all things, caution and planning should be used to implement it in the most effective fashion.

Related devCity.NET articles:

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.37499999999999 out of 5
 48 people have rated this page
Article Score56505
Comments    Submit Comment

Comment #1  (Posted by Mohammed Al-Shibli on 07/22/2002)

Hi all of ya

I really appreciate MS for its new VB.Net . I was thinking about doing such things in vb6 without any result.

This is a good article about this topic. I am thankfull to Dear Writer !.

THANX again. Dont forget to SMILE :).
 
Comment #2  (Posted by Prakash M Shenoy on 07/27/2002)

Help!!!

Unable to view the derived form. When I try to open the derived form in the design window I am getting the following error:

An error occured while loading the document. Fix the error, and then try loading the document again. The error message follows:

The designer could not be shown for this file because none of the classes within it can
be designed. The designer inspected the following classes in the file:
formInheritedCompanyStandard -- The base class
'StandardCompanyForms.formOKCancel' could not be loaded. Ensure the assembly
has been referenced or built if it is part of the project.

The same error occurs for the sample example on MS site.

Please help.

Thanks
Prakash
 
Comment #3  (Posted by Monty Nail on 07/28/2002)

You may have missed the following step from the article:

"Rebuild (recompile) your project. This step is very important. When the project is rebuilt the code is output in a DLL instead of an EXE. If you don't do this step you will not be able to inherit the form in another project."

You can do this by selecting the StandardCompanyForms project in the Solutions Explorer, then on the main menu select "Build
 
Comment #4  (Posted by Prakash M Shenoy on 07/29/2002)

Thank you for a quick response.

I did rebuid the project. I am seeing the same error. The program runs successfully except that I can not view the inherited forms in design window. I tried rebuilding each project separately. No luck.

I also tried my own code. It is the same. Do you think this is a bug in Visual Studio. Net?

I am stuck with this and really dont know how to proceed.

Any suggestions will be greatly appreicated.

Thanks once again.
Prakash
 
Comment #5  (Posted by Prakash M Shenoy on 07/29/2002)

Thank you for a quick response.

I did rebuid the project. I am seeing the same error. The program runs successfully except that I can not view the inherited forms in design window. I tried rebuilding each project separately. No luck.

I also tried my own code. It is the same. Do you think this is a bug in Visual Studio. Net?

I am stuck with this and really dont know how to proceed.

Any suggestions will be greatly appreicated.

Thanks once again.
Prakash
 
Comment #6  (Posted by Monty Nail on 07/29/2002)

Look in the Solutions Explorer under the CustomForms project, then under the Reference. Does StandardCompanyForms appears as a reference there (along with System, System.Data, etc.)? Does the EXE in the "\BIN\Debug" folder run successfully on your machine?

I downloaded the code that is posted with the site and was able to use it from two different machines. Both were on WinXP, though I previously used it on Win2K.

My version of Visual Studio is the Enterprise Architect, but I don't think that should matter.
 
Comment #7  (Posted by Mike on 09/05/2002)

Great article and it actually works.
 
Comment #8  (Posted by Yizhong Wang on 01/04/2003)

I got the same error message as Prakash. I could run the sample zip without any problem. I just couldn't see the design view of the derived form.
 
Comment #9  (Posted by Daffs on 04/10/2003)

Hi,

I encountered a problem in visual inheritance.
I had a base form which read some configuration informations like color and font from a application configuration file.
This base form was inherited by child forms.
But am not able to open the child forms in the design mode.
The configuration setting for the base form was done in the load method.
Any help?
Thanks

 
Comment #10  (Posted by Melisa Lang on 06/30/2003)

I get the same error message using C# as the others. I was unable to view the design of the inherited form and got the message: The designer could not be shown for this file because none of the classes within it can be designed.

And yes, I did build the first project as a class library...

What is wrong?
 
Comment #11  (Posted by coco on 07/22/2003)

For your problems, put the project wich will contain the inherited form in the default visual studio folder (myDocuments/Visual Studio Projects) and this'll work!

But I don't know why... any idea?

 
Comment #12  (Posted by Paule on 01/12/2004)

That "solution" doesn't seem to work. It has nothing to do with "MyDocuments" location anyway. The problem still exists. I can repro it 100% of the time. If you run into this problem, you can remove your reference to the DLL that you are using (temporarily comment out any depended code on the DLL), save the project, and all of a sudden, the form can now be opened in design view again!

The interesting thing is that if you add the reference back and rebuild the project, it will throw an error on each control that you have on the form. Each error message says it cannot find the control, WHEN IN FACT THEY ARE THERE! In the form designer, all your controls get blow away too. If you then find all the control declarations in the form code (e.g., "private System.Windows.Forms.Label label1;") do the following:

1. Select all the control declarations and CUT them.
2. Save and build the project. (disregard any errors).
3. Then, past the form code back in.

Now, when you go back to the design view, the controls will be back. How magical! Unfortunately, when you now rebuild the project with the references back in, you will still have the same problem!
 
Comment #13  (Posted by Hui on 01/29/2004)

I had some problem when inherit form from .Dll.
Error message:
Unable to add reference 'appname' to the current application. Check that a different version of 'appname' is not already referenced.

Any suggestion?
 
Comment #14  (Posted by Alex on 02/02/2004)

To Hui:

I have this problem in my project.
I added inherited form in the same project where the ancestor is declared and then moved it to another project. It works. But I still cant add inherited form in another project directly. Seems like a bug in VS?
 
Comment #15  (Posted by Siva on 02/07/2004)

Follow these steps:
1. close all the opened forms
2. goto references of the project
3. select all assemblies referenced by the project
4. go to properties and then set local copy to false
5. now open up the form in design mode and it should work.
Good Luck
Siva


 
Comment #16  (Posted by CYB on 04/02/2004)

Hi There
I am having the same problems on Win2K and apparently I cannot get the designer onto the screen.
Can someone pls kindly help me pls.
I have tried all the above mentioned though.
Many thx
CYB
 
Comment #17  (Posted by Andy tate on 04/23/2004)

Ensure that you don't have "#" listed as part of your code path:

i.e. "C:\Code Samples\C# samples\Visual Inheritance\"

If you re-name to something like CSharp, you should find that this overcomes the issue..

Rgds, Andy
 
Comment #18  (Posted by AN on 06/01/2004)

Thanks Siva, your comments helped me get out of this problem even a year later
 
Comment #19  (Posted by marco on 06/25/2004)

Hi there,

I have a problem i have created a dll WinUibase and added a form with a panel dock bottom and 2 buttons "ok and cancel" I set all the modifiers to "protected"
then in another project i inherit from the base form add some controls rebuild and the ok and cancel buttons dissappears also the form resizes and sometimes i can only see o1 button

any ideas?

thanks
 
Comment #20  (Posted by DeviSingh on 08/12/2004)

I designed an asp.net web application project in C#. I added a class library project to it. In the class library project I designed a component class. Now when I inherit any new class from the component class, it does not allow me to see the design view of the newly created class. The project builds with no errors.
Any help is welcome..
Regards
 
Comment #21  (Posted by Marcus on 03/01/2005)

Setting all Reverences to CopyLocal: False
fixes the problem for me

thx
 
Comment #22  (Posted by Sonny on 03/15/2005)
Rating
Siva, you are the man
 
Comment #23  (Posted by Parminder Dhaliwal on 04/01/2005)
Rating
If you can not see the usercontrol or form in design view, make sure the following line exists in the InitializeComponent

components = new System.ComponentModel.Container();

 
Comment #24  (Posted by Kevin on 06/17/2005)
Rating
Silva, you are my hero. And now, I'll be everyone else's hero here at work! This has been driving me up the wall for weeks!!
 
Comment #25  (Posted by an unknown user on 06/21/2005)
Rating
i need more information
1 System ABC
Ing. Raul Avila
cesar_avila78@hotmail.com
 
Comment #26  (Posted by Lynne on 06/30/2005)
Rating
If it helps anyone, I tried all the suggestions listed above but still couldn't see my inherited form in the designer - it was just showing the icon and minimize, maximize and full screen buttons. The problem I found was caused by having set the WindowState in the parent form to Maximized. When I reset it to Normal (and rebuilt), the inherited form became visible. My suggestion is, start with a simple form and add each control one at a time until you find the one which stops you from being able to see the inherited form.
 
Comment #27  (Posted by Jod on 08/20/2005)
Rating
Ive had the same issue, and i just found a really simple way around it! It seems the DLL you are inheriting from must be a Debug DLL to show in designer! I was always performing a release build of the custom form, then referencing that. It seems if you reference the debug build, all works fine :)

At release time for your main project, you would use a release build of the dependencies.
 
Comment #28  (Posted by an unknown user on 08/24/2005)
Rating
i dont want this
 
Comment #29  (Posted by Pankaj on 10/13/2005)
Rating
I am unable to find the events for the controls placed in the main form.
Only the default events are available on clicking the control.
Not able to find names of events associated with the inherited form.
 
Comment #30  (Posted by RB on 10/14/2005)

Make sure you have a "using" statement at the top of your inherited form .cs file which references the class library dll of the parent form hierarchy.
 
Comment #31  (Posted by Sundar on 11/27/2005)
Rating
Good example. Very clear instructions. Thanks!
 
Comment #32  (Posted by an unknown user on 01/09/2006)
Rating
Very good code and explanation of it.
 
Comment #33  (Posted by Jonn on 02/13/2006)
Rating
Hi! How to me to adjust a background of page?
 
Comment #34  (Posted by Andry on 02/13/2006)
Rating
Hi
More more of such sites.

Thanks
 
Comment #35  (Posted by The Mad Coder on 07/09/2006)
Rating
You can only visually inherit from a form defined in an .exe if it is in the same project. The MSDN documentation is misleading because it does not mention this.

To visually inherit from a form defined in another project (even if it is in another solution) you will have to build that project as a class library (.dll). This is necessary because the project where you are adding the "Inherited Form" (should be called Inheriting Form imho) needs to reference the library (.dll)


 
Comment #36  (Posted by an unknown user on 08/24/2006)
Rating
Hi,
I add an inherited form to one of my project in the same, it run well. But if i remove it from the project removing all the refrenced assemblies, it was fine. But if i try to add the same inherited form with the same name that i gave last time, i found error like 'this name exist in your project, use another name'.
 
Comment #37  (Posted by Nazim Raza on 08/24/2006)
Rating
Hi,
I add an inherited form to one of my project in the same, it run well. But if i remove it from the project removing all the refrenced assemblies, it was fine. But if i try to add the same inherited form with the same name that i gave last time, i found error like 'this name exist in your project, use another name'.
 
Comment #38  (Posted by an unknown user on 10/27/2006)
Rating
would like to see discussion of the side effects of anchoring bottom/right on inherited forms. see rweilgelt's blogs.
 
Comment #39  (Posted by an unknown user on 10/27/2006)
Rating
would like to see discussion of the side effects of anchoring bottom/right on inherited forms. see rweilgelt's blogs.
 
Comment #40  (Posted by an unknown user on 11/12/2006)
Rating
code is working properly without any error.
how to generate a property window at runtime for textbox control

 
Comment #41  (Posted by an unknown user on 02/13/2007)
Rating
Can I inherit a form in VB6 that I created in .Net? After creating the Dll program in .Net, I was unable to add it as a reference in a VB6 project
 
Comment #42  (Posted by an unknown user on 04/11/2007)
Rating
in figure two forms are shown ,,but when i added the inherit from..only onr id visible in ma solution explorer

 
Comment #43  (Posted by an unknown user on 04/22/2007)
Rating
I was having trouble moving forms from one application to another.

Unlike VB6 where you can just move a form from one project to another, vbNet will not allow it. I was having to completely rebuild each form in each application. What a pain.

This not only solved the problem it has opened many doors for future development.

Many thanks to Monty Nail for his article.

Gary O'Connor.
 
Comment #44  (Posted by an unknown user on 04/27/2007)
Rating
Good detail on inheritance & the little things you need to do to make it work with a base form.
 
Comment #45  (Posted by João Marques on 05/22/2007)
Rating
I had the same problem.
I had created an inherated Form from another one and it wasn't designed in VS.

But now I just resolved the probme :D

My namespace of the project has the same name as the nameof the project.
I changed the name of namespace to another one and rebuilt the project.

Then it worked :D

I hope that this can help you.
(Sory my bad english, I hope you can understand what I said)
 
Comment #46  (Posted by João Marques on 05/23/2007)
Rating
Another possible help.

I've created Form1.
Then I've created Form4 that inherited Form1.
Cause de Form1 doesn't had the default constructor Form1() without any argument Form4 couldn't found the constructor of Form1 and couldn't be designed.

Then I've created the default constructor Form1() and it begans to work.

Hope that this can help you.
Good work.
 
Comment #47  (Posted by an unknown user on 08/28/2007)
Rating
Nice little intro
 
Comment #48  (Posted by Cisjokey on 04/02/2008)
Rating
Hello Dear

First; Comments should only be comments, not support requests ;-)

For all other.

- I had to unload all solutions in my Visual Studio expect this which should contain the derived form. (If you do not unload all, you may have to redo the other steps for all opened projects in your solution.)
- Then clean the project!
- Then rebuild the project.

This has worked, i had quite similiar issues as many developers posting previously.

Greetings
 
Comment #49  (Posted by an unknown user on 06/05/2008)
Rating
Nice starting point. I also like the tip about creating a basic applciation first than changing it to a Assembly.. Very nice.
 
Comment #50  (Posted by an unknown user on 06/17/2008)
Rating
Doesn't cover enough of the modifiers property.
 
Comment #51  (Posted by an unknown user on 07/28/2008)
Rating
awesome i learn about the button coding
 
Comment #52  (Posted by an unknown user on 04/18/2009)
Rating
dear monty

its a great article and solves many issues and saves time as i have to copy/paste such
controls from one form to another to give same look & feel

also, these buttons are not accessed in the user form. how can i process different actions when save button (of base form) is called means this button has different
actions to follow. or how can i override the default code??

could you please also mail me this solution at sushil.soni@hotmail.com

thanking you with best regards,
Sushil Soni
 
Comment #53  (Posted by on 10/11/2009)
Rating

 
Comment #54  (Posted by Coder11 on 10/22/2009)
Rating
This led to three posts on my own blog: first, second, third. ,
 
Comment #55  (Posted by Polh on 11/25/2009)
Rating
I found it very interesting.: URLsWithHREF
 
Comment #56  (Posted by Velopli on 11/28/2009)
Rating
I really do like this place.: URLsWithNothing
 
Sponsored Links