Inheritance and Windows Forms

VB.net is now considered an object oriented language with the new core changes in the language carried by Microsoft in this new edition of Visual basic. The object oriented programming has proven itself to be very powerful, robust, and beautiful to work with. Well, enough theories and marketing stuff and let’s get to the real thing! In this article we will not be only talking about a class’s inheritance, but will also take advantage of the Windows form inheritance that was produced Visual Studio.NET. (Yes, the forms are classes and can be inherited.) Let’s get on with it!

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 26
January 26, 2004
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Let’s say that we are developing software for a mobiles company. We have technicians, and we certainly have some managers. As a matter of fact, both the technicians and the managers are employees in this mobiles company. Employees have names, and Age (for simplicity).  Managers do management activities, and Technicians do the technical activities. So if we want to put this into code, then we will have the following:

1) Employee Class: which have the most common things between the Managers and technicians, in our case, the name and age.

2) Manager Class: since the manager is in essence and Employee, then this class will inherit its basics from the Employee Class.

3) Technician Class: again, a Technician is an Employee, and this class should inherit its basics from the Employee Class.

So far, so good. Straight forward implementation, to be sure - but where is the beef?

Well, since out application is to work with the objects mentioned above, then yes, what you are thinking of is true; there should be some windows forms to help me interact with these objects. So we will be talking about a very basic form that will enable the users from adding new Manager, Technician, in other words and Employee.

Go ahead and download the project and open the solution to have a better understanding about what’s going on. As you can see, we have three classes in the “Classes” folder under the project, which contain (as expected) the Employee class, with a Name and an Age, and the other two classes that are inheriting from the Employee class: Manager and Technician.

Exploring Forms

Now let’s explore the “Forms” folder in under the project. As you can see, there are three forms: “ManageEmployees”, “ManageManagers”, and “ManageTechnicians”. If you view the code in the “ManageManagers” or the “ManageTechnicians” forms, then you will see that these forms inherit from the “ManageEmployees” form.

Here is how we add an inherited form.

1) Right click on the project and select “Add” -> “Add Windows Form”, and name it “ManageEmployees”

2) Before adding the inherited form, make sure you “Build” the project.

3) Right click on the project and select “Add” -> “Add Inherited Form”, and name it “ManageManagers”. In the “Inherit Picker” chose the form that we want to inherit from , and in this case it is “ManageEmployees”
4) Do the same step for the form “ManageTechnicians”.

What we have done so far is the following:

1) We added classes “Manager” and “Technician”, which inherit from the “Employee” Class.

2) We added forms “ManageManagers” and “ManageTechnicians”, which inherit from the “ManageEmployees”.

Now, here is the beauty of the inheritance in windows form. We will be working on the “ManageEmployees” form only, and this will be reflected on the other forms since we have the inheritance relation (remember?).

1) Let’s set some properties on the “ManageEmployees” form:
    a. ControlBox = False
    b. FormBorderStyle = FixedDialog.
2) Add 2 labels to the form (lblName, lblAge).
3) Add 2 text boxes to the form (txtName, txtAge).
4) Add a button (btnAdd).
5) And finally add an Error Provider (errProvider).

If you want to set the properties of the controls on the form, then please check them on the project.

Before we move on, please make sure to “Build” the project. If you check the “ManageManagers” or the “ManageTechnicians” forms, you will find out that they have the same properties and the controls that are available on the “ManageEmployees” form. No magic was done, it is the inheritance.

Validating Inputs

So far we managed to have 2 forms, with the same basic controls and functionality, much like the “Employee” class and the other inherited classes “Manager” and “Technician”. It shouldn’t stop here, should it?

Uhm, no.

As a matter of fact, if I am adding a Manager, or a Technician, then I want to validate the inputs. We will not, however, make the validation on each form alone (remember the “ManageEmployee” Form). We will put the validation code and make use of the error provider on the “ManageEmployee” form.

We will add a function “IsValidInputs” which will validate the user inputs in the text boxes. It will also set the set the properties of the error provider if any errors were found.


Protected Function IsValidInputs() As Boolean
        Dim strEmployeeName 
As String
        Dim strEmployeeAge 
As String 
'Age should be integer, but not we will be reading from the' 
'text box, and we need to validate that it is an integer'
        Dim bIsValidInputs 
As Boolean True 
'we start with the assumption that the inputs are valid'
        
Try
            
strEmployeeName txtName.Text.Trim
            strEmployeeAge 
txtAge.Text.Trim
            
'check if the Name is empty'
            
If strEmployeeName String.Empty Then
                bIsValidInputs 
False
                errProvider
.SetError(txtName"Please add a Name.")
            Else
                
'Make sure to clear the Error Provider
                errProvider.SetError(txtName, "")
            End If
            If strEmployeeAge = String.Empty Then
                bIsValidInputs = False
                errProvider.SetError(txtAge, "Please add an Age.")
            Else
                '
Make sure to clear the Error Provider'
                errProvider.SetError(txtAge, "")
            End If
            If Not IsNumeric(strEmployeeAge) Then
                bIsValidInputs = False
                errProvider.SetError(txtAge, "Age should be a number.")
            Else
                '
Make sure to clear the Error Provider'
                errProvider.SetError(txtAge, "")
            End If
            Return bIsValidInputs
        Catch oException As Exception
            '
Handle any unexpected errors here'
        End Try
    End Function

Let’s get back to the object oriented. The function above should be only visible to the form and the forms inheriting from it. (Yes, it should be protected.)

Carrying Out the Scenario

Well, here is the scenario that I want to carry out:

1) I want to add a manager.
2) I want to validate the user inputs.
3) If the user inputs are valid, then I want to add the manager.

The same scenario above should be valid for the technicians.

The most logical way to carry out the previous scenario for the manager is to validate the inputs when the user clicks the “Add” (btnAdd). But if we handle it on the “ManageEmployees” form, then how should I determine if what I am adding is a Manager or a Technician? One of the answers will be to put an enum on the form and set it to the type of employees I am working with.

Shouldn’t I check all the time about this enum, no matter what I do? We will thank the “ManageEmployees” form for giving us the common functionality and our “ManageManagers” form should be taking over from now on.

But before we take over, we will be asking our nice “ManageEmployees” form a final request, that please, when you receive the click event of button “btnAdd” we want to handle that event.

So, if you double click on the “btnAdd” on the “ManageEmployees” from the editor will open to this sub.


Private Sub btnAdd_Click(ByVal sender As System.Object
ByVal e 
As System.EventArgsHandles btnAdd.Click
 
End Sub

As you can tell, the “btnAdd_Click” is private, and according to the Object Oriented principles, this means that the sub will be only available to the class itself.

Should we stop here (for sure not!!) we will do a little change on this sub to look just like this:


Protected Overridable Sub btnAdd_Click(ByVal 
sender 
As System.ObjectByVal e As 
System
.EventArgsHandles btnAdd.Click
 
End Sub

Now the sub looks much better. It is not only available to the “ManageEmployees” form only, but also to all the forms that are inheriting from the “ManageManagers” and “ManageTechnicians” (yes you are right, it is Protected). Above all, it is ready to be taken control off by the inheriting classes (it is Overridable).

So let’s get back to our “ManageMangers” form, and let’s override the “BtnAdd_Click” sub. Let’s add the following to the “ManageManagers”:


Protected Overrides Sub btnAdd_Click(ByVal sender 
As System
.ObjectByVal e As System.EventArgs
'Handles btnAdd.Click
 
End Sub

Explanation

As you can tell, we overrode the sub in the base class. So that when the user click the “Add” button, on the “ManageEmployee” form, our “ManageManagers” form will take over, and do its work. Note that we commented the “Handles btnAdd.Click.” Why?

Good question. Remember that we are overriding a sub in the parent class, and the event is being captured on the parent class, so in the child class we don’t receive the event. Rather, it is being received by the parent class.

Since the first thing we want to do before creating a new manager is to validate the user inputs, and since the function that validates the user inputs is in the parent class “ManageEmployees”, then we will call our parent “IsValidInputs” which will determine if the inputs are valid and if we can go on with our work. So the “btnAdd_Click” sub will just look as beautiful as this:


Protected Overrides Sub btnAdd_Click(ByVal 
sender 
As System.ObjectByVal e As 
System
.EventArgs'Handles btnAdd.Click
     Dim oManager As Manager
     Try
         If IsValidInputs() Then
             oManager = New Manager(MyBase.txtName.ToString,
Integer.Parse(MyBase.txtAge.ToString))
         End If
     Catch oException As Exception
         '
Handle any unexpected errors here
     End Try
 End Sub

Always remember that any change on the parent form “ManageEmployee” should be followed by a “Build” to the project in order to carry out the changes on the inheriting forms.

This is just a glance on how to use the windows forms and the inheritance between forms: we wrote the general code on a parent form, and then used it with the child forms. Now if we want to add more fields, add extra functionality, change some logic, or even play with the properties of the form - so we only need to change it on the parent form - build the project, and the changes will automatically be reflected on the children forms.

blog comments powered by Disqus
VISUAL BASIC.NET ARTICLES

- Basic Form Properties and Modality in VB.NET
- Multiple Document Interfaces in Visual Basic
- Visual Basic for Beginners
- ASP.NET Image to PDF with VB.Net
- MySQL in ASP.NET: Mono using VB.NET
- AsyncFileUpload File Type and File Size Vali...
- Visual Studio: Adding Functionality and Style
- Clocks and Countdowns
- User-defined Functions using Visual Basic Ap...
- Understanding Object Binding in VBA
- Mastering the Message Box
- Testing a Windows Forms Application
- Using Visual Basic.NET Features to Code a Wi...
- Correcting Code in a Windows Forms Applicati...
- Write Readable Code and Comments for Windows...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials