Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / Visual Basic
Article

Everything you wanted to know about Forms Inheritance in VB.NET - “Best”

Rate me:
Please Sign up or sign in to vote.
3.40/5 (38 votes)
19 Oct 20039 min read 171.4K   2.3K   34   23
How to edit the properties of the inherited control in the form in design time.

Sample Image - BestFormInheritance.jpg

Table of contents

  • What is the need of Forms Inheritance
  • Introduction
  • Concept of Inheritance
  • Visual Inheritance
  • How to inherit the form
  • How to make custom properties
  • How to use custom properties from the child form
  • How to change the properties of the controls from the parent form, which are not in the parent form (i.e. they are in the child forms)
  • How to override the functionality of the parent form from the child form
  • How to change the properties of the inherited controls at design time (i.e. how to reposition the controls, set different properties, etc.)

What is the need of Forms Inheritance?

So, the biggest question before reading this article - what is the need of Forms inheritance.

First, we will be coding all the base/common code into the Base form (any Form from which we want to inherit). Then instead of copying or writing some global functions to change the properties or call methods, etc. to use some functionality of the base form (as we use to do in our earlier Languages), we can use form inheritance here.

We can inherit the base form into the form where we want to implement the common functionality. As we inherit the form all the public/protected functionality of the base form gets merged into child form.

For example: In a common scene, we have to design navigationa panel in our application to navigate from one record to another. Previously to avoid the repeatable code we use ActiveX Control. First we deisgn the activeX Control for the navigation and then we place this onto our form where we wanted to implement the functionality.

But this time, we can code the functionality of the navigation panel in the base form and then inherit this form to achieve a similar in the child and make the best use of Form inheritance.

Most of the times, when we want to give the functionality of navigational panels, status bars, info labels, etc in your project you can use form inheritance there. Code all these in the Base form and then inherit the base form into the forms where you want to implement the same functionality. If you want you cal also override some/all functionality of the Base forms from the child forms without affecting the base form.

Now you have the answer why you should read this article. So, guys you can enjoy reading.

Introduction

The major change occurred for the VB programmers, when Microsoft announced the launch of their new VB.NET to become the best successor for our most favorite programming language Visual Basic.

What VB lacks was the power of INHERITANCE, so Microsoft decided to implement inheritance in VB.NET. Every time we need a new form in our applications we create a new instance of the System.Windows.Forms.Form class, change its properties to suit our needs. Place some controls and our form is ready for use. As we know, by placing some controls on to a new form, we extend the forms class to NewForm1 means we have created a new class with a name NewForm1. Our new form is a class, we can extend any class due to inheritance supported in .NET.

So from this we can conclude that we can design the base form and use the base form design in all our forms.

Like we have,

Base form:

VB
Public Class PMainForm
    Inherits System.Windows.Forms.Form

Child forms:

VB
Public Class ChildForm
    Inherits PmainForm

Now we can use the Child Forms in the ways we desired. Things we can do with our child forms: override the functionality of the base form within the child form itself (i.e. using Shadows keyword in our functions in the child form – we will also see this in details later in this article), we can add custom properties to our base form and set them in the child forms (for controlling the controls which originally does not exists in the parent form) and everything which we want.

Concept of Inheritance

I know that, OO Programmers must know each and everything of INHERITANCE. This section is especially for the non-OO based Programmers, so the experienced OO programmers can skip this section.

Definition (Inheritance): Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say "A inherits from B''. Objects of class A thus have access to attributes and methods of class B without the need to redefine them. The following definition defines two terms with which we are able to refer to participating classes when they use inheritance.

Definition (Superclass/Subclass): If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.

Superclasses are called parent classes. Subclasses may be called child classes or just derived classes.

Of course, you can again inherit from a subclass, making this class the superclass of the new subclass. This leads to a hierarchy of superclass/subclass relationships. If you draw this hierarchy you get an inheritance graph.

A common drawing scheme is to use arrowed lines to indicate the inheritance relationship between two classes or objects.

Visual Inheritance

We know how to create objects of classes. Just in a similar fashion, we can also inherit a form and I swear I am not kidding.

Is it possible to inherit the components of the parent form?

Yes, it is possible. But inheriting the controls does not means that we are able to view the controls in the child forms, because we inherits the controls but not the properties of those controls which we had set into the Parent form. Means suppose we have placed one Button in the Parent form. And its Top position is at 200px. This does not depicts that if we inherit the Parent Form for the child class then we will be able to see the same Button at the same position (i.e. Button1.Top = 200)

So, how does this all happen? How we are able to see the controls of the parent form at the same location in the child form.

VS.NET does this by repositioning the controls in the child form. You can experience this. Go and change the position in the Parent Form and don’t build the Parent form. Now open the Child Form and see the difference in the position of the Button, it is at the older position.

Means, the position of the button has not changed even if we have changed it in the parent form. So what VS.NET does it resets the properties of the Controls in the Child Form, when we compile the Parent Form.

Now you all know how VS.NET incorporates Visual Inheritance.

What’s new in this article

If you simply inherit the form, you will not be able to change the properties of the Controls which you have placed in the base form. This example covers:

  1. How to inherit the form?
  2. How make custom properties?
  3. How to use the custom properties from the Child form?
  4. How you change the properties of the controls from the parent form, which are not in the parent form (i.e. they are in the Child forms)?
  5. How to override the functionality of the Parent form from the Child Form?
  6. How to change the properties of the inherited controls at design time? (I.e. how to reposition the controls, sets different properties, etc)
 
  1. How to inherit the form?

    Open the child form and replace the Child Form’s Inherits line to <name of the parent form> from <System.Windows.Forms.Form>

    Base form:

    VB
    Public Class PMainForm
        Inherits System.Windows.Forms.Form

    Child forms:

    VB
    Public Class ChildForm
        Inherits PmainForm
  2. How to make custom properties?

    Open the Parent Form and create a property (having a scope as Protected Friend)

    VB
     'CurrentPosition Property
     Dim LPosition As Long
     Protected Property Position() As Long
         Get
             Return LPosition
         End Get
         Set(ByVal Value As Long)
             LPosition = Value
         End Set
     End Property
    
  3. How to use the custom properties from the Child form?

    Open the child Form. Use Me.<propertyName> to change the property. For ex. : we are changing the property in the Load event of the child form.

    VB
    Private Sub CForm3_Load(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles MyBase.Load
            Me.Position = 99
    End Sub
  4. How you change the properties of the controls from the parent form, which are not in the parent form (i.e. they are in the Child forms)?

    Open the Parent Form define a property which accepts <Control> as return type.

    VB
     'InfoLabel Property (Control which
    'we want to use from the child form)
     Dim localLabel As Label
     Protected Property InfoLabel() As Label
         Get
             Return localLabel
         End Get
         Set(ByVal Value As Label)
             localLabel = Value
         End Set
     End Property
    

    Now, open the child form. Place the control, which you want to use with the Parent Form. Change the ControlProperty from the Child Form for the parent form, in any event of the child form. For this example I have done this in the load event of the child form.

    VB
    Private Sub CForm3_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
        Me.InfoLabel = Label1 
        'Control to be controlled by the Parent Form
        
        Me.Position = 99
    End Sub
  5. How to override the functionality of the Parent form from the Child Form?

    Override that function of the parent form, which handles the particular functionality (for ex. click event of the button in the parent form).

    If you copy n paste that function from the Parent Form. Please don’t forget to add the Shadows Attribute, for suppressing the function of the Parent Form (Note: when we use the Shadows keyword, then there is no need to use the Overridable keyword in the Parent Form for that function)

    Parent form:

    Child Form:

    VB
    'Overiding the implementation of the Parent Form
    'please don't forget to remove the handles keyword from the last while
    'implementing in the child form
     
    Protected Friend Overrides Sub BParent_Click(ByVal sender _ 
        As System.Object, ByVal e As System.EventArgs)
    MsgBox("Functionality of Child is used.")
    End Sub

    Or

    VB
    Protected Friend Shadows Sub BParent_Click(ByVal _ 
           sender As System.Object, ByVal e As System.EventArgs)
      MsgBox("Functionality of Child is used.")
    End Sub
  6. How to change the properties of the inherited controls at design time? (i.e. how to reposition the controls, sets different properties, etc)

    The main problem, when we inherit any ParentForm - its very simple. Change the Modifiers property of the control, we want to control from the Child Form from Friend to Protected Friend.

Note: Protected Friend will be not listed there, so please take some pains and perform the following steps.

  1. Open the Code Window for the Parent Form.
  2. Expand " Windows Form Designer generated code " section.
  3. Find InitializeComponent() function.
    VB
    <System.Diagnostics.DebuggerStepThrough()> _ 
      Private Sub InitializeComponent()
  4. Above this function you will find the initialization code for the controls which we have been placed into the form. They will be like:
    VB
    'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents PBNavPrev As System.Windows.Forms.Button
        Friend WithEvents NavCaption As System.Windows.Forms.Label
     
        Friend WithEvents BParent As System.Windows.Forms.Button
        Friend WithEvents NavPanel As System.Windows.Forms.Panel
        <System.Diagnostics.DebuggerStepThrough()> _ 
          Private Sub InitializeComponent()

    change to access modifiers of the control to Protected Friend for sharing them in the child form.

  5. VB
    'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Protected Friend WithEvents Button1 As System.Windows.Forms.Button
        Protected Friend WithEvents PBNavPrev As System.Windows.Forms.Button
        Protected Friend WithEvents NavCaption As System.Windows.Forms.Label
     
        Protected Friend WithEvents BParent As System.Windows.Forms.Button
        Protected Friend WithEvents NavPanel As System.Windows.Forms.Panel
        <System.Diagnostics.DebuggerStepThrough()> _
           Private Sub InitializeComponent()
 

For full understanding of the concept you can download the accompanying application. This will provide you with the better view of forms inheritance.

Well, that's it folks. Hopefully, this article will give the better understanding of how the forms inheritance works internally. And how avail the benefits of Visual Form Inheritance functionality of VS.NET.

And please don’t forget to rate this article, so that I can continue writing, improve myself and present you something “best”. Feel free to ask me at saurabh.verma@india.rsystems.com for any queries. I will feel very great. You can read the whole article from the Readme.doc provided with the download.

So, now go n enjoy the things. I will be back soon with some “best” code example for ADO.NET, till then take care. Bye.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Saurabh Verma works as an Architect, possessing over 10 years designing and developing software and currently assists product companies to scale and writing flexible software. He has vast experience in designing Web 2.0 solutions using Microsoft Technologies; WF, WCF and AJAX.ASP.NET, and practicing AGILE Methodologies and Domain Driven Design for the implementation. He likes to perform superbike stunts in his free time. Smile | :)

He has been awarded Microsoft Most Valuable Professional, MCSD.NET, MCAD.NET, MCDBA and Microsoft Web Rock Star 2007.

He maintains his blog at http://www.domaindrivendesign.info for all the aspiring architects and developers.

You can reach him at saurabhdotnet@hotmail.com

Comments and Discussions

 
QuestionHow to move inherited button in design time ? Pin
Member 103457563-Jan-18 6:09
Member 103457563-Jan-18 6:09 
GeneralMy vote of 5 Pin
jmeekuk12-Mar-13 1:49
jmeekuk12-Mar-13 1:49 
QuestionGreat! Pin
Member 859537328-Aug-12 1:56
Member 859537328-Aug-12 1:56 
GeneralMy vote of 5 Pin
aaroncampf29-Feb-12 10:22
aaroncampf29-Feb-12 10:22 
GeneralQuery Pin
xxx 201221-Sep-09 0:59
xxx 201221-Sep-09 0:59 
QuestionForms Inheritance in C# Pin
sjpjs12-Sep-07 20:38
sjpjs12-Sep-07 20:38 
Questionso how can u do this? Pin
K edar V6-Sep-06 2:49
K edar V6-Sep-06 2:49 
Generalnice article! Pin
nathan_rasch1-Sep-06 8:44
nathan_rasch1-Sep-06 8:44 
GeneralThanks Pin
Coding1234569-Apr-06 2:18
Coding1234569-Apr-06 2:18 
GeneralRe: Thanks Pin
Nasenbaaer11-Nov-08 1:19
Nasenbaaer11-Nov-08 1:19 
GeneralWhy the article was rated so poorly Pin
Tom Clement27-Mar-04 6:33
professionalTom Clement27-Mar-04 6:33 
AnswerRe: Why the article was rated so poorly Pin
Saurabhdotnet6-Jan-08 3:37
Saurabhdotnet6-Jan-08 3:37 
GeneralStill more article color problems... Pin
ZoogieZork12-Nov-03 10:23
ZoogieZork12-Nov-03 10:23 
GeneralWhy inherit forms Pin
forecasting21-Oct-03 12:42
forecasting21-Oct-03 12:42 
GeneralRe: Why inherit forms Pin
Saurabhdotnet21-Oct-03 21:16
Saurabhdotnet21-Oct-03 21:16 
GeneralA suggestion Pin
Michael P Butler19-Oct-03 22:03
Michael P Butler19-Oct-03 22:03 
GeneralSo... Pin
Daniel Turini19-Oct-03 21:40
Daniel Turini19-Oct-03 21:40 
GeneralMy EYES! Pin
NormDroid19-Oct-03 21:21
professionalNormDroid19-Oct-03 21:21 
GeneralRe: My EYES! Pin
Saurabhdotnet20-Oct-03 8:01
Saurabhdotnet20-Oct-03 8:01 
General*argh* Pin
Uwe Keim19-Oct-03 20:57
sitebuilderUwe Keim19-Oct-03 20:57 
GeneralRe: *argh* Pin
Roger Alsing19-Oct-03 21:29
Roger Alsing19-Oct-03 21:29 
GeneralRe: *argh* Pin
Saurabhdotnet20-Oct-03 8:03
Saurabhdotnet20-Oct-03 8:03 
GeneralRe: *argh* Pin
Saurabhdotnet20-Oct-03 8:03
Saurabhdotnet20-Oct-03 8:03 
Article updated. Yellow color problem solved. Please read and rate.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.