Chapter 1 vb.net
Chapter 1 vb.net
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.
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.
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.
7. In the Properties window, click the BackColor property, and then click
the down-arrow button in the adjacent text box.
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.
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
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
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.
Text will display in Label when Form gets executed.Main event of Label is the Click
event.
When you click on the Text Hello written in Label then click event will fire and
messagebox will display the message.
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:
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
Output:
14
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.
Figure
Chapter 1 Introducing Windows Forms 15
Now double click on the simple button and add the following code.
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
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.
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
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
End Sub
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
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.
• 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
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.
• 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:
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
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
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.
• 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:
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.
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:
Now we have run the test and csUnit indicates that there must be some functionality missing in
our program.
Fine, that is the expected behaviour. Now we can add functionality to the Add method:
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 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
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!
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:
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:
.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:
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.
If you change the Person definition to look like the preceding line, Student will no longer be
able to inherit from Person.
If you changed Person to include the MustInherit keyword, it would look like this:
32
Now, you would not be able to use the following line of code in the client:
However, you would still be able to inherit Person in your Student class, and your client could
instantiate Student.
If you want to allow a property or method to be overridden, you can mark it with the
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:
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
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.
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 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:
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:
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.
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:
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:
PerformMovement(MyCar)
PerformMovement(MyBike)
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
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
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.
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.
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
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
Output
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
Output
46
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.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.