0% found this document useful (0 votes)
2 views

Chapter 1 vb.net

This document introduces Windows Forms in VB.NET, covering the creation of applications, implementation of controls, and event handling. It provides step-by-step instructions for setting up a Windows Forms application, modifying properties, and adding various controls like labels, text boxes, checkboxes, and buttons. Additionally, it explains how to handle events and interact with user inputs through code.

Uploaded by

hello4mjeba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 1 vb.net

This document introduces Windows Forms in VB.NET, covering the creation of applications, implementation of controls, and event handling. It provides step-by-step instructions for setting up a Windows Forms application, modifying properties, and adding various controls like labels, text boxes, checkboxes, and buttons. Additionally, it explains how to handle events and interact with user inputs through code.

Uploaded by

hello4mjeba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 1 Introducing Windows Forms 1

UNIT 1 Introducing of WindowsForms

Structure Page Nos.


1.0 Objectives
1.1 Introduction
1.2 Creating a Windows Forms Application
1.3 Implementing Class Library Object
1.4 Vb.Net implementation of Inheritances
1.5 Namespaces
1.6 Summary
1.7 Questions for Exercise
1.8 Suggested Readings

1.0 Objective:
 Create Windows Forms applications.
 Use common Windows Forms controls such as labels, text boxes, and buttons.
 Change the properties of Windows Forms and controls at design
time and programmatically at run time.
 Subscribe to and process events exposed by Windows Forms and controls.

1.1 Introduction:
In this unit you will learn how to create windows form in vb.net, uses of different
windows controls on the form, setting their properties and handling the events of the
form controls. , all these controls are basically a graphical object. These graphics
objects help the user to interact with an application in a friendly way You will learn
2

about the creation of class library, implementation of inheritance and the uses of
namespaces.

1.2 Creating a Windows Forms Application


In this exercise, you’ll start building the Middleshire Bell Ringers Association
application by creating a new project, laying out the form, and adding Windows
Forms controls to the form. Because you have been using existing Windows
Forms applications in Microsoft Visual Studio 2005 in previous chapters, much
of the first couple of exercises will be a review for you.

Create the sharemarket Association project


1. Start Visual Studio 2005.
2. On the File menu, point to New, and then click Project.
3. In the Project Types pane, select Visual C#.
4. In the Templates pane, select Windows Application.
5. In the Name text box, type share market.
6. In the Location list box, navigate to the Microsoft Press\Visual
CSharp Step by Step\
7. Click OK.
The new project is created and contains a blank form called Form1.
Chapter 1 Introducing Windows Forms 3

Set the properties of the form

1. Select the form in the Designer View window. In the Properties


window, click the (Name) property, and then type MemberForm in the
(Name) text box to change the name of the form. (If the Properties
window is not displayed, click Properties Window on the View menu,
or press F4.)

2. In the Properties window, click the Text property, and then type share
market, to change the text in the title bar of the form.

3. In the Properties window, click the BackgroundImage property, and


then click the Ellipses button in the adjacent text box.

The Select Resource dialog box opens.

4. In the Select Resource dialog box, click Local resource and then
click Import. The Open dialog box opens.
5. In the Open dialog box, navigate to the My Documents folder, select
the image.gif file, and then click Open.
4

Part of the image will be displayed in the Select Resource dialog box.

6. In the Select Resource dialog box, click OK.

The BackgroundImage property is now set to the image.

7. In the Properties window, click the BackColor property, and then click
the down-arrow button in the adjacent text box.

A dialog box opens.

8. On the System tab of the dialog box, click Window. This value sets
the background color of all the controls that you drop onto the form to
the same color as the window itself.

9. Select the Font property. This is a composite property that has many
attributes. In the Properties window, click the plus sign (+) to expand
the Font property and display the attributes. Type 12 for the Size
attribute of the font, and set the Bold attribute to True.

Tip You can also change some composite properties, such as Font, by clicking the
ellipses button that appears when you select the property. When you click the ellipses
button in the Font property, the standard Font dialog box opens and allows you to select
the font and effects that you want.

10. Change the form’s Size property, which is also a composite property. In
the Properties window, click the plus sign (+) to expand the Size
property and display the attributes. Set the Width attribute to 600 and
the Height attribute to 470.
Chapter 1 Introducing Windows Forms 5

The form should look like the image in the following graphic.

On the Build menu, click Build Solution. The form should build successfully.
11. On the Debug menu, click Start Without Debugging.
The application will start running and will display the main form containing the image.
The form does not do anything useful yet, so close it and return to Visual Studio.

What Are the Common Windows Forms Properties?


If you look closely at the Properties window when a form is selected, you can
see that there are over fifty properties available. Some of them are fairly
obvious; for example, the Text property that corresponds to the text displayed
in the form’s title bar. Some properties are useful under certain circumstances;
for example, you can remove the Minimize, Maximize, and Close but- tons, or
remove the System menu from the title bar of a form by setting the ControlBox
prop- erty to False—useful if you want to ensure users cannot close the form
unless they execute some code that closes it explicitly. Other properties apply
to very specific circumstances; for example, the Opacity property can be used
to control the level of transparency of the form. The following table describes
6

some of the common form properties that you can change at design time. You
should also be aware that there are additional properties not listed in the
Properties window that you can use only programmatically at run time. For
example, the ActiveControl property shows which control in the form
currently has the focus.

Property Description
(Name) The name of the form. Two forms in the same project cannot

have the same name.


BackColor The default background color of any text and graphics in the form.
BackgroundImage A bitmap, icon, or other graphic file to be used as a backdrop
to the form. If the image is smaller than the form, it can be tiled
to fill the form, stretched, centered, or zoomed by using the
BackgroundImageLayout property.
Font The default font used by the controls embedded on the form
that display text. This is a compound property—you can set
many attributes of the font including the font name, size, and
whether the font appears italic, bold, or underlined.

ForeColor The default foreground color of any text and graphics in the form.
FormBorderStyle This controls the appearance and type of border of the form. The
default set- ting is Sizable. Other options specify borders that
are not resizable or do not have the various System menu
buttons.
Icon This specifies the icon that appears in the form’s System menu
and on the Mi- crosoft Windows taskbar. You can create your
own icons by using Visual Stu- dio 2005.
Location This is another compound property that specifies the
coordinates of the top left corner of the form with respect to its
container, which might be another form or the screen.
MaximizeBox This property specifies whether the Maximize command on the

System menu and caption bar is enabled or disabled. By


default, it is enabled.
MaximumSize This specifies the maximum size of the form. The default value
(0, 0) indicates that there is no maximum size and the user can
resize the form to any size.
Chapter 1 Introducing Windows Forms 7

MinimizeBox This property is similar to the MaximizeBox property. It


specifies whether the Minimize command on the System menu
and title bar is enabled or disabled. By default, it is enabled.
MinimumSize This property specifies the minimum size of the form.

Property Description

Size This is the default size of the form when it is first displayed.
Text This property contains the text that appears on the title bar of the
form.
WindowState This property determines the initial state of the form when it is
first displayed. The default state (Normal) positions the form
according to the Location and Size properties. The other
options are Minimized and Maximized.

Adding Controls to the Form


So far you have created a form, set some of its properties, and examined the
code that Visual Studio 2005 generates. To make the form useful, you need to
add controls and write some code of your own. The Windows Forms library
contains a varied collection of controls. The purposes of some are fairly
obvious—for example, Label, TextBox,, CheckBox, radioButton, ListBox and
ComboBox etc.

The Label Control


Let's create a label by dragging a Label control from the Toolbox and dropping it on the
form.
8

Display Text in Label.

Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load
'display text in Label
Label1.Text = "Hello"
End Sub

Text will display in Label when Form gets executed.Main event of Label is the Click
event.

Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Label1.Click
'MessageBox will show message
MessageBox.Show("How are you")
End Sub
Chapter 1 Introducing Windows Forms 9

When you click on the Text Hello written in Label then click event will fire and
messagebox will display the message.

Label Control Properties ForeColor:

ForeColor of Label can be changed through ForeColor Property of Label.

Private Sub Form6_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load
'change Label ForeColor
Label1.ForeColor = Color.Red
End Sub

2. The TextBox Control


Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on
the form.

Example
10

In this example, we create three text boxes and use the Click event of a button to display
the entered text using a message box. Take the following steps:

Drag and drop three Label controls and three TextBox controls on the form.

Change the texts on the labels to: Name, Organization and Comments, respectively.

Change the names of the text boxes to txtName, txtOrg and txtComment, respectively.

Drag and drop a button control on the form. Set its name to btnMessage and its text
property to 'Send Message'.

Click the button to add the Click event in the code window and add the following code.

PublicClassForm1
PrivateSubForm1_Load(sender AsObject, e AsEventArgs) _
HandlesMyBase.Load
' Set the caption bar text of the form.
Me.Text = "NOU.com"
End Sub
Private Sub btnMessage_Click(sender As Object, e As EventArgs) _
Handles btnMessage.Click
MessageBox.Show("Thank you " + txtName.Text + " from " + txtOrg.Text)
End Sub End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
Chapter 1 Introducing Windows Forms 11

Clicking the Send Message button would show the following message box:

3. The CheckBox and RadioButton Controls


CheckBox code:
Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles CheckBox1.Click
' The CheckBox control's Text property is changed each time the
' control is clicked, indicating a checked or unchecked state.
If CheckBox1.Checked = True Then
CheckBox1.Text = "Checked"
Else
CheckBox1.Text = "Unchecked"
12

End If
End Sub

Output :

The form will look like bolow when we drag RadioButton controls on the forms
Chapter 1 Introducing Windows Forms 13

Then we put this code on the double click of the submit button and reset button

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArg


s) Handles Button1.Click
If RadioButton1.Checked Then
TextBox1.Text = "You Clicked" & " " & RadioButton1.Text()
ElseIf RadioButton2.Checked Then
TextBox1.Text = "Your Clicked" & " " & RadioButton2.Text()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArg
s) Handles Button2.Click
TextBox1.Text = ""
End Sub
End Class

Output:
14

The Button, LinkButton, and ImageButton Controls

For example:

Write a web form to create two label Number and Result. Now create two text boxes, one
to input a number and other to output a number. Now create three different buttons as
simple button, image button and link button to
show Square, SquareRoot and CubeRoot of give number.

The form looks like this:

Figure
Chapter 1 Introducing Windows Forms 15

Now double click on the simple button and add the following code.

Protected Sub cmdSquare_Click(ByVal sender As Object, ByVal e As EventArgs) Handles


cmdSquare.Click
Dim num As Double = Double.Parse(txtNumber.Text)
Dim sq As Double = num * num
txtResult.Text = sq.ToString()
End Sub

Now double click on the LinkButton and add the following code.
Protected Sub cmdSquareRoot_Click(ByVal sender As Object, ByVal e As EventArgs) Ha
ndles cmdSquareRoot.Click
Dim num As Double = Double.Parse(txtNumber.Text)
Dim sq As Double = Math.Pow(num, 1.0 / 2)
txtResult.Text = sq.ToString()
End Sub

Now double click on the ImageButton and add the following code.
Protected Sub cmdCubeRoot_Click(ByVal sender As Object, ByVal e As System.Web.UI.I
mageClickEventArgs) HandlescmdCubeRoot.Click
Dim num As Double = Double.Parse(txtNumber.Text)
Dim sq As Double = Math.Pow(num, 1.0 / 3)
txtResult.Text = sq.ToString()
End Sub

Now save and run the application.

The List Controls


Let's create a list box by dragging a ListBox control from the Toolbox and
dropping it on the form.
16

You can populate the list box items either from the properties window or at
runtime. To add items to a ListBox, select the ListBox control and get to the
properties window, for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box,
where you can enter the values one at a line.

Example
In the following example, let us add a list box at design time and add items on it at
runtime.

Take the following steps:

Drag and drop two labels, a button and a ListBox control on the form.

Set the Text property of the first label to provide the caption "Choose your favourite
destination for higher studies".

Set the Text property of the second label to provide the caption "Destination". The text on
this label will change at runtime when the user selects an item on the list.

Click the listbox and the button controls to add the following codes in the code editor.
Chapter 1 Introducing Windows Forms 17

PublicClassForm1

PrivateSubForm1_Load(sender AsObject, e AsEventArgs)HandlesMyBase.Load

' Set the caption bar text of the form.

Me.Text = "tutorialspont.com"

ListBox1.Items.Add("Canada")

ListBox1.Items.Add("USA")

ListBox1.Items.Add("UK")

ListBox1.Items.Add("Japan")

ListBox1.Items.Add("Russia")

ListBox1.Items.Add("China")

ListBox1.Items.Add("India")

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

MsgBox("You have selected " + ListBox1.SelectedItem.ToString())

End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)

Handles ListBox1.SelectedIndexChanged
18

Label2.Text = ListBox1.SelectedItem.ToString()

End Sub

End Class

When the above code is executed and run using Start button available at the Microsoft
Visual Studio tool bar, it will show the following window:

When the user chooses a destination, the text in the second label changes:
Chapter 1 Introducing Windows Forms 19

Clicking the Select button displays a message box with the user's choice:
20

Run the Application


1. On the Debug menu, click Start Without Debugging to run the application.
2. Type in a first name and a last name, and then select a tower from the list. Click Add. In
the message box that appears displaying the member data you entered, click OK.
3. Try and close the form. In the message box that appears, click No.
The form should continue running.
4. Try and close the form again. In the message box, click Yes.
This time the form closes and the application finishes.

1.3 Implementing Class Library Object

Class: A class allows you to create objects of the class. A class can be defined with data
fields, properties, methods and events. You can create objects based on that class that have
state (fields, properties) and behavior (methods, events). A class can be considered as a
specification of how the object of the class should look like and behave.

An object of the class is nothing other than a sequence of bytes at a specific memory location
in the memory heap. Thus we can understand that an object is an instance of the class. We can
see an illustration of a class.

Create the solution

• Open VS.NET
• Select "File New Blank Solution" from the Pull down menu.
Then you will see the "New Project" Window
• Enter "MyCalculator" as the solution name
• Specify a folder of your choice to store the solution in
Chapter 1 Introducing Windows Forms 21

• Click "OK" and the empty solution will be created

Create the test project

We have an empty solution. Now our first step will be to set up the project which contains the
tests. This project will be a class library because csUnit does not need a special entry point.

It will find test methods through the attributes we give them.

• Select "File Add Project New Project Visual Basic Projects Class
Library"
• Enter "MyCalculatorTests" as the name
• Click "OK"
• Unfortunately VS.NET always creates its default class (called "Class1") when you add
a project. It has shown to be the fastest way to delete this class and to add the own ones
later. So we delete "Class1" from the project (you can do this by right-clicking on the
class name in the Solution Explorer and selecting "Delete").
22
• The solution contains one empty project now and should look like this:

Create the class library project

Now we will set up the project which we are going to test. The Steps are the same as for the
test project:

• Select "File Add Project New Project Visual Basic Projects Class
Library"
• Enter "MyCalculator" as the name
• Click "OK"
• Remove "Class1" from the project

Set up references for the test project

In order to let the test project know where it can find the classes that it shall use (csUnit classes
and the classes from the class library to be tested) we need to set up references to these
Projects/Assemblies.
Chapter 1 Introducing Windows Forms 23

• In the Solution Explorer Right-Click the "References" node of the project


"MyCalculatorTests"
• Select "Add Reference ..."
• In the .NET tab select the item with the component name "csUnit" by double clicking
or by marking it with a left mouse click and pressing the "Select" button:

• In the Projects tab select "MyCalculator" as reference to be added:

• Now click "OK"


• The tree for the test project should look like this in the solution explorer now:
24

Create a Test Fixture

Now let's go to the real task. In this step we will set up a test fixture. A test fixture is a class
which contains test methods which will be executed by csUnit.

• First we create a new class in the test project:


Select "File Add New Item Class"
• Enter "BasicArithmeticsTests.vb" as the name

• Click "Open"
• Now you should see the new class in the code window.

To define this class as a test fixture we need to assign the corresponding csUnit attribute now.
Modify the class code like this:
Imports csUnit
<TestFixture()> _
Public Class BasicArithmeticsTests

End Class
The imports statement tells VB.NET to import the csUnit namespace which contains the
TestFixture Attribute.
Add a Test

Now the big moment has come. We are going to create the first test. Our first test consists of
the following code:

Imports csUnit
Imports MyCalculator

<TestFixture()> _
Public Class BasicArithmeticsTests
<Test()> _
Public Sub Add()
Chapter 1 Introducing Windows Forms 25
Dim ba As BasicArithmetics
ba = New BasicArithmetics()
Assert.Equals(3, ba.Add(1, 2))
End Sub
End Class
Note: The <:Test()> attribute tells csUnit that the Sub "Add" shall be executed by csUnit as a
test.

As soon as you try to build this you will see that the compiler does not like it. There isn't a
BasicArithmetics class.

Let us do something against that: Create a new class called "BasicArithmetics" in the project
"MyCalculator". Initially this class shall have the following code:

Public Class BasicArithmetics


Public Function Add(ByVal num1 As Integer, _
ByVal num2 As Integer) As Integer
Add = 0
End Function
End Class
Yes, you are right. This Add method will always return a 0.

We strongly recommend you to write tests in such an order that you have seen each test as
failed (red) before you add the functionality to make the test successful (green). That is the
only way to make sure that the program does exactly what the tests demand.

Now the first test and the first part of the program are written. The Solution should build now.
Then we can go on and run the test.

Run the Test bar red

Before we run the tests please make sure that the test project is defined as StartUp project. This
is the case if the project name of the test project "MyCalculatorTests" is written in bold letters
in the solution explorer. If this is not the case right-click on the project name and select "Set as
StartUp Project".
26

This is necessary for csUnit to know in which project it shall look for tests. Running the tests is
simple:

• From the Tools menu select "csUnit for Visual Studio".

Then csUnit should start up.


• Click on "Run" and (hopefully) you will see this:

Now we have run the test and csUnit indicates that there must be some functionality missing in
our program.

Write class library code


Chapter 1 Introducing Windows Forms 27
In the previous step csUnit reported us that the expected result had been 3 but actually the
program returned 0.

Fine, that is the expected behaviour. Now we can add functionality to the Add method:

Public Class BasicArithmetics


Public Function Add(ByVal num1 As Integer, _
ByVal num2 As Integer) As Integer
Add = num1 + num2
End Function
End Class

Run the Test again bar green

Now we build the program again and then we start csUnit (If it is still open you can use the
open instance. csUnit reloads all classes on each test run so that changes are considered).

The result looks like this:

The green bar indicates that no test reported a problem and that the program works perfectly
(at least in the areas which are being covered by tests; hopefully there are no different areas).
28

1.4 VB.NET’s Implementation Inheritance

One thing to realize is that in VB.NET, all classes are inheritable by default. This includes
forms, which are just a type of class. This means you can create a new form based on an
existing form.

Inheritance Example
Create a new VB.NET Windows Application project and name it InheritanceTest. Add a button
to the form and go to the code window. In the code, add the following class. Make sure that
you add it outside the class for the form!

Public Class Person

Dim localName, localAddress As String

Property Name() As String


Get
Name = localName
End Get
Set(ByVal Value As String)
localName = Value
End Set
End Property

Property Address() As String


Get
Address = localAddress
End Get
Set(ByVal Value As String)
localAddress = Value
End Set
End Property
Chapter 1 Introducing Windows Forms 29

Public Function Enroll() As Boolean


‘check class enrollment
‘if enrollment < max. class size then
‘enroll person in class
Enroll = True
End Function
End Class
This code creates a Person class with two properties, Name and Address, and an Enroll
method. So far, there is nothing about this class that you haven’t seen before.
Now, add a second class, called Student. Your code should look like this
Public Class Student
Inherits Person
End Class

As you can see, there isn’t any implementation code in Student at all. There are no properties
or methods defined. Instead, all you do is inherit from Person.

Now, in the Button1_Click event handler on the form, add the following code:

Dim Student As New Student()


MsgBox(Student.Enroll)

Your form is creating an instance of the Student class. The only code in the Student class is an
Inherits statement that inherits the Person class. However, because VB.NET supports
inheritance, you’ll be able to call the Enroll method of the Person class from within the Student
class, even though the Person class does not explicitly define an Enroll method. Instead, the
Enroll method is present because Student is inheriting the method from Person. Go ahead and
run the project to verify that the message box does report back a value of True.

Is it possible to instantiate Person directly? In this case, yes. For example, you could modify
the Button1_Click event handler to look like this:

Dim Student As New Student()


30

Dim Person As New Person()


MsgBox(Student.Enroll & “ - from Student”)
MsgBox(Person.Enroll & “ - from Person”)

Both of these calls to the Enroll method will work fine.

.Shared Members

VB.NET introduces the concept of shared members. Shared members are a way of cre-ating a
member (a property, procedure, or field) that is shared among all instances of a class. For
example, you could create a property for a database connection string. This will be the same for
each class, so you can fill it in for one class and all classes can then see
that one property. Shared properties are most often used in inheritance, so that all objects
created from derived classes can share the same member across all instances of the class.
However, shared members can be used without regard to inheritance.
Imagine that you have an XML file or other persistence mechanism for the student data listed
earlier, and you want to define a method to be able to find a student, given his name, and return
the student object. Rather than the COM model of having a factory to create the object, you
could add the Find functionality as a shared method to the student class. For example:

Public Class Student


Inherits Person

Public Shared Function Find(ByVal studentName As String) _ As Student

Dim Student As New Student()


Dim xmlobj As Xml.XmlElement
‘get the xml object
‘fill in the mName field
‘fill in the mAddress field
Return Student
End Function
End Class
Chapter 1 Introducing Windows Forms 31

Shared methods are commonly used in the runtime for this ability to create a specific instance
of an object, for example System.IO.CreateDirectory() that will create a directory in the file
system, and return a DirectoryInfo object. The same System.IO. Directory class also provides a
shared method, Move, to rename a directory.

Inheritance Keywords
There are a number of keywords associated with inheritance. Remember that by default, all
classes you create are inheritable. You inherit from classes using the Inherits keyword. The
class from which you inherit is then known as the base class. The Inherits keyword can be used
only in classes and interfaces. It is important to point out that a derived class can only inherit
from one base class.

Forcing or Preventing Inheritance


The NotInheritable modifier is used to mark a class as not inheritable; in other words, it cannot
be used as a base class. If you were to modify the Person class in your InheritanceTest project,
it would look like this:

Public NotInheritable Class Person

If you change the Person definition to look like the preceding line, Student will no longer be
able to inherit from Person.

In contrast to the NotInheritable modifier, there is also a MustInherit modifier. MustInherit


says that a class cannot be instantiated directly. Instead, it must be inherited by a derived class,
and the derived class can be instantiated.

If you changed Person to include the MustInherit keyword, it would look like this:
32

Public MustInherit Class Person

Now, you would not be able to use the following line of code in the client:

Dim Person As New Person

However, you would still be able to inherit Person in your Student class, and your client could
instantiate Student.

Overriding Properties and Methods


When you inherit a base class, the properties and methods cannot be overridden, by default.
Given your earlier example in InheritanceTest, you could not have created a function named
Enroll in Student because one existed in Person. There is a modi-fier, NotOverridable, that says
a particular property or method cannot be overridden. Although methods are normally not
overridable, you can use this keyword only in a unique case: If you have a method that is
already overriding a base method, you can mark the new, derived method as NotOverridable.

If you want to allow a property or method to be overridden, you can mark it with the

Overridable modifier, as shown here:

Public Overridable Function Enroll() As Boolean

Now, your Student can create its own Enroll method. To do so, your client will have to use the
Overrides modifier, so it would look like this:

Public Overrides Function Enroll() As Boolean


Chapter 1 Introducing Windows Forms 33

In the VB.NET IDE, it is also possible to use the drop-down lists at the top of the code window
to override methods or implement interfaces.

There is also a MustOverride modifier. This forces a derived class to override the property or
method. The MustOverride modifier changes the structure of the prop-erty or method. Because
the property or method must be overridden, you do not put any implementation code in it. In
fact, there is not even an End Property or End Sub or End Function when using the
MustOverride modifier. If a class has even a single property or method with the MustOverride
modifier, that class must be marked as MustInherit.
For example, here you have a base Transportation class that has a method, Move, that is
marked as MustOverride. This means that Transportation must be marked as MustInherit. The
Train class inherits from Transportation, and then overrides the Move method.
Public MustInherit Class Transportation

MustOverride Function Move() As Boolean

End Class

Public Class Train


Inherits Transportation
Public Overrides Function Move() As Boolean
‘code goes here
End Function
End Class

Although you can override a base class property or method in your derived class, you can still
access the properties or methods in the base class using the MyBase keyword. This allows you
to call base classes members even though you have overridden them in your derived class.

For example, assume you wanted to have a Transportation class, with an overrid-able function
called Move. Train then inherits from Transportation, and implements its own Move method,
overriding the one in Transportation. However, Train can call its Move method or the one in
34

Transportation. The method CallMethods calls first the Move in Train, and then the Move in
Transportation. The user will see two message boxes. The first will have the text Hello from
the Train class, whereas the second will have the text Hello from the Transportation class.

Public Class Transportation


Overridable Function Move() As Boolean
MsgBox(“Hello from the Transportation class”)
End Function
End Class

Public Class Train


Inherits Transportation
Public Overrides Function Move() As Boolean
MsgBox(“Hello from the Train class”)
End Function

Public Sub CallMethods()


Move()
MyBase.Move()
End Sub
End Class

Related to MyBase is MyClass. Assume that, in your base class, you have method A calling an
overridable method B. If you want to verify that the method B you call is the one you wrote in
the base class, and not the derived, overridden method B in the derived class, call method B
with the MyClass qualifier, as in MyClass.B.

For example, assume that you have a Transportation class that has two methods:

MakeReservation and BuyTicket. MakeReservation calls BuyTicket.


Chapter 1 Introducing Windows Forms 35

MakeReservation and BuyTicket are both overridable. Your Train class can inherit
Transportation, and create a BuyTicket method that overrides the BuyTicket in Transportation.
If you don’t create a MakeReservation in Train, your call to MakeReservation will use the code
in the Transportation class. However, if the code in Transportation.MakeReservation calls
BuyTicket, by default you’ll call the BuyTicket you’ve created in Train. Here is the code:

Public Class Transportation


Overridable Function MakeReservation() As Boolean
‘CheckSchedule
BuyTicket()
‘etc
End Function
Overridable Function BuyTicket() As Boolean MsgBox(“Generic
Transportation implementation”)
End Function
End Class

Public Class Train


Inherits Transportation

Public Overrides Function BuyTicket() As Boolean


MsgBox(“Train-specific implementation”)
End Function
End Class

Now, suppose that you want the MakeReservation to call the BuyTicket method in
Transportation, even if Train overrides BuyTicket. To accomplish this, just change

Transportation.MakeReservation to this:

Public Class Transportation


Overridable Function MakeReservation() As Boolean
‘CheckSchedule
MyClass.BuyTicket()
‘etc
End Function
36

In this case, if your client calls Train.MakeReservation, the MakeReservation method will call
the BuyTicket in the base class (Transportation) instead of the overridden BuyTicket (if one
exists in Train). However, it’s important to note that if your Train class overrides
MakeReservation, MyClass will not come into play. This is because you will be calling the
overridden MakeReservation, which won’t include the MyClass keyword.

Polymorphism
Polymorphism is the ability to change the implementation of a base class for different objects.
For example, if you have a bicycle and a car, both can move, but they do
so in very different ways. They use different mechanisms for movement, and the distance that
each can move in an hour is significantly different. Yet, both a Car and a Bike class might
inherit from a base Transportation class, which could also be used as the basis for a Plane class,
a Train class, a HotAirBalloon class, and so on.

Polymorphism with Inheritance


Polymorphism was possible in VB6 using interfaces, which will be examined in a moment.
VB.NET allows you to perform polymorphism using inheritance. The dif-ference from what
you have done so far is that you can actually use the base class as a variable type, and you can
handle any derived class with that new variable.

For example, examine the following code. The Transportation class contains just one method,
Move. Two classes inherit the Transportation class: Car and Bicycle. Both have overridden the
Move method. The code looks like this:

Public MustInherit Class Transportation


Public MustOverride Function Move() As Boolean
End Class

Public Class Bicycle


Inherits Transportation
Overrides Function Move() As Boolean
‘code here
Chapter 1 Introducing Windows Forms 37

Move = True
End Function
End Class

Public Class Car


Inherits Transportation
Overrides Function Move() As Boolean
‘different code here
Move = True
End Function
End Class

So far, this looks similar. However, notice now what your client can do. It cannot directly
create an instance of Transportation because it is marked as MustInherit. But, you can declare a
variable of type Transportation. You can be assured that any object that inherits Transportation
has a Move method, and you don’t have to worry about what kind of object it is. Your client
code might look like this:

Protected Sub Button1_Click _


(ByVal sender As Object, ByVal e As System.EventArgs)
Dim MyCar As New Car()
Dim MyBike As New Bicycle()

PerformMovement(MyCar)
PerformMovement(MyBike)
End Sub

Public Sub PerformMovement(ByVal Vehicle As Transportation)


If Vehicle.Move() Then
‘do something
End If
End Sub

You’ll notice that the PerformMovement sub accepts an argument of type Transportation. This
sub doesn’t care if you pass it an object of Car or Bicycle type. Because the object being
passed in inherits from Transportation, it is guaran-teed to support the Move method, so the
code will run without problems.
38

Polymorphism with Interfaces


Interfaces still exist in VB.NET. In VB6 and COM, they were most often used when you
needed to be able to modify your code without breaking existing clients. You could actually
modify the structure of your classes, but provide an interface that looks like the old version of
the component. This kept existing client applications happy while at the same time you were
able to modify the classes to enhance functionality.

In VB.NET, you can still use interfaces this way. However, interfaces are best used when you
want to be able to use different object types in the same way, and the objects don’t necessarily
share the same base type. For example, the IEnumerable interface is used to expose an
enumerator for a class. Using this interface, you can move through a class using For Each, even
if the class is not based on a Collection object.

You’ll see an example of polymorphism with interfaces using the same example of the Car and
the Bicycle. First, Transportation will be created as an interface instead of a base class, which
might make more sense: The Move method is most likely to be quite different between a car
and bicycle. Then, you’ll implement the Transportation interface. Finally, you’ll call the
objects from the client.

Interface Transportation
Function Move() As Boolean
End Interface

Public Class Bicycle


Implements Transportation
Function Move() As Boolean Implements Transportation.Move
‘code here
Move = True
End Function
End Class
Chapter 1 Introducing Windows Forms 39

Public Class Car


Implements Transportation
Function Move() As Boolean Implements Transportation.Move
‘ different code here Move = True
End Function
End Class

You’ll notice that now, when you implement from an interface, you don’t have to use the
Overrides modifier. In addition, the method definition is followed by an Implements keyword
that specifies which method in the interface the current method is implementing. This allows
you to have different names for the methods in the class that is implementing the interface. The
client code here will be the same as it is when you use inheritance polymorphism.

1.5 Visual Studio.NET Namespaces

Software projects consist of several pieces of code such as classes, declarations, procedures and
functions etc., known as the component or identifiers of the software project. In large projects
the number of these components can be very large. These components can be grouped into
smaller subcategories. This logical grouping construct is known as a "Namespace" or we can
say that the group of code having a specific name is a "Namespace". In a Namespace the
groups of components are somehow related to each other. Namespaces are similar in concept to
a folder in a computer file system. Like folders, namespaces enable classes to have a unique
name or we can say that it is a logical naming scheme for grouping related types. A Namespace
is sometimes also called a name scope. An identifier defined in a Namespace belongs to that
Namespace and the same identifier can be independently defined in multiple Namespaces with
a different or the same meaning. Every project in C# or VB.NET starts with a Namespace, by
default the same name as the name of the project.
40

Why we need it

We must add a reference of the Namespace object before using that object in a project. Several
references are automatically added in the project by default. The VB.Net "Imports" keyword is
used to add a reference of a namespace manually.

Example

1. Imports System

Note: Imports allow access to classes in the referenced Namespace only not in its internal or
child Namespaces. If we want to access internal Namespace we might need to write:

1. Imports System.Collections

Namespaces are basically used to avoid naming collisions, when we have multiple classes with
the same name, and it is also helpful for organizing classes libraries in a hierarchal structure.
Namespaces allow us to organize Classes so that they can be easily accessed in other
applications. Namespaces also enable reusability.

A class in .Net Framework cannot belong to multiple Namespaces. One class should belong to
only one Namespace. VB.NET does not allow two classes with the same name to be used in a
program.

We can define a Namespace using the "Namespace" keyword. The syntax for declaring a
Namespace is:

1. Namespace <Namespace_name>
2.
3. // Classes and/or structs and/or enums etc.
4.
5. End Namespace

Example
Chapter 1 Introducing Windows Forms 41

Note: All the classes in the .Net Framework belongs to the System Namespace. The "system"
Namespace has built-in VB functionality and all other Namespaces are based on this "system"
Namespace.

Accessing Members of a Namespace

We can access a member of a Namespace by using a dot(.) operator, also known as the period
operator. The members of a Namespace are the variables, procedures and classes that are
defined within a Namespace. To access the member of a namespace in a desired location type
the name of the namespace followed by the dot or period operator followed by the desired
member of the namespace.

Example

MyNamespace.Class1.disp() 'Accessing elements of the MyNamspace

we can access a member of a namespace in various ways. The following program


shows accessing the element of a namespace in various ways.

1. Imports System
2. Namespace Birds 'user defined namespace Bird
3. Class Parrot 'Parrot is a class in the namespace Animals
4. Public Shared Function fly() 'Fly is a function in this
Class
5. Console.WriteLine("Parrot can fly")
6. End Function
7. Public Shared Function color() ' color is another functi
on in parrot class
8. Console.WriteLine("normally Parrots are green")
9. End Function
10. Public Shared Function type()
11. Console.WriteLine("Different type of parrot ar
e found around the world")
12. End Function
13. End Class
14. End Namespace
15.
16. Module Module1
17. Public Function myfunction()
42

18. Dim P As Birds.Parrot


19. P = New Birds.Parrot()
20. P.type() 'accessing member of the namespace bi
rd
21. End Function
22. Sub main()
23. Console.Clear()
24. Birds.Parrot.fly() 'accessing member of the
namespace
25. ConsoleApplication5.Birds.Parrot.color() 'another
way to access member of the namespace
26. myfunction()
27. End Sub
28. End Module

Output

1. Namespace MyNamespace 'class with in a namespac


e
2. Public Class Class1
3. Public Shared Function disp() 'function declared w
ithin the class
4. Console.Write("hello" & vbCrLf)
5. End Function
6. End Class
7. End Namespace

Nesting a Namespace
Chapter 1 Introducing Windows Forms 43

Nesting a Namespace means create a namespace inside a namespace. A good way to organize
namespaces is to put them in a hierarchal order, i.e. general name at the top of the hierarchy
and put specific names at the lower level.

Example

1. Imports System
2. Namespace outer 'declare an outer namespace
3. Public Class nameout
4. Public Shared Function disp() 'create a function inside
a outer namespace
5. Console.WriteLine("hi this is outer name space")
6. End Function
7. End Class
8.
9. Namespace inner 'decalre an inner namespace
10. Public Class nameinn
11. Public Shared Function disp() 'create a funct
ion inside the inner namespace
12. Console.WriteLine("hi this is inner namesp
ace")
13. End Function
14. End Class
15. End Namespace
16.
17. End Namespace
18.
19. Module module1
20. Sub main()
21. Console.Clear()
22. outer.nameout.disp() 'accesing function of
the outer namespace
23. outer.inner.nameinn.disp() 'accessing fucntion of
the inner namespace
24. End Sub
25. End Module

Output
44

Note: You can not have two classes with the same name in the same scope. In other words,
class overloading is not allowed.

Example

1. Namespace MyNamespace
2. Public Class one 'sample class with in a namespace
3. Public Shared Function disp() 'function declared within
the class
4. Console.Write("hello" & vbCrLf)
5. End Function
6. End Class
7.
8. Public Class one 'this is not allowed
9. Public Shared Function disp1()
10. Console.Write("hi")
11. End Function
12. End Class
13. End Namespace

You can avoid this by putting classes with the same name in a different scope.

Example
Chapter 1 Introducing Windows Forms 45

1. Namespace outerscope 'sample class with in a namespace

2. Public Class one


3. Public Shared Function disp() 'function declared within
the class
4. Console.Write("hello class with outerscope" & vbCrLf
)
5. End Function
6. End Class
7. Namespace innerscope
8. Public Class one 'same class with different scope
9. Public Shared Function disp1()
10. Console.Write("hi this class is wihtin inn
erscope of outscope namespace " & vbCrLf)
11. End Function
12. End Class
13. End Namespace
14. End Namespace
15.
16. Module module1
17. Sub main()
18. Console.Clear()
19. outerscope.one.disp()
20. outerscope.innerscope.one.disp1()
21. End Sub
22. End Module

Output
46

Aliases of the Namespaces

Aliases are created when we have nested Namespaces. It is easy to access the members of the
namespaces by the alias. An alias is a shortcut for a nested namespace with a shorter label. An
alias of a namespace is created with the help of the "imports" keyword. Aliasing is useful when
we are working with a large project.

Example

1. Imports ally = ConsoleApplication6.outerscope.innerscope 'creati


ng an alias name for inner scope
2. Namespace outerscope 'sample class with in a namespace

3. Public Class one


4. Public Shared Function disp() 'function declared within
the class
5. Console.Write("hello class with outer scope" & vbCrL
f)
6. End Function
7. End Class
8. Namespace innerscope
9. Public Class one 'same class with different scope
10. Public Shared Function disp1()
11. Console.Write("hi accessing the member wit
h the alias name" & vbCrLf)
Chapter 1 Introducing Windows Forms 47

12. End Function


13. End Class
14. End Namespace
15. End Namespace
16.
17. Module module1
18. Sub main()
19. Console.Clear()
20. outerscope.one.disp() 'accessing member of the ou
terscope namespace without alias name
21. ally.one.disp1() 'accessing member of the inn
erscope by alias name
22. End Sub
23. End Module

1.6 Summary
In Windows application, Form is going to act as a container to hold various controls.
Check box and Radio buttons are provides the user with group of choices. But check Box
supports multiple choices whereas the Radio button is mutually exclusive.
List and Combo box list the group of items that the user can select. Difference between
these two is the combo has in build place holder for user’s selection.
As you can see, setting up inheritance is not difficult. However, the challenge comes when you
design your components and your object model. Inheritance is quite pow-erful, but you must
intelligently define your base classes to make them broad enough to be inheritable, but general
enough to be useful to many derived classes.

With the introduction of implementation inheritance, VB.NET moves into the realm of
object-oriented (OO) languages for the first time. VB6 had some OO constructs, but the
addition of implementation inheritance, one of the most basic OO concepts, greatly
strengthens VB.NET’s OO portfolio.with the help of namespaces we can include the class
library into your applications.

1.7 Questions for Exercises


48

1. Design a window form application for the registration in NOU


2. Explain different fundamental properties & methods of Window forms
3. Explain the implementation of class library in vb.net?
5. Explain the implementation of inheritance in vb.net?

6. What is namespaces? Why we need it?

1.8 Suggested Readings:


Visual Basic Tutorial
• http://www.vbtutor.net/VB2008Book/vb2008me_preview.pdf
• http://www.functionx.com/vbnet/Lesson03.htm
• http://vb.net-informations.com/gui/windows_forms.htm
Chapter 1 Introducing Windows Forms 49

You might also like