Вы находитесь на странице: 1из 65

Class, Objects, Application

We will define classes, use the defined classes, to


make an application
Concepts used are:
•Class
•Array
•Stream

Prepared by :
Somnath Mukherjee
(MCTS, MCPD, MCAD, MCSD)
Let us launch the Microsoft Visual Basic 2010 Express. Create a solution. Add a Windows
Form, name it as you like, here I have named it as Form9.vb.
Now add a MenuStrip from the Tool box.
Type the menu options a shown below, like main menu item is Contact List and its child
items are Add a Contact, Delete a Contact etc.
Add a DataGridView from the toolbox and name it as dg
Change the Anchor property as Top, Left, Bottom, Right,
Right so that the DataGridView will
occupy the space of the form with a specified margin.
Click on the small expander button (triangle), this will show you the extended options
related to the DataGridView, as shown below. Un-Checked the Enable Adding,
Adding Enable
Editing,
Editing Enable Deleting.
Deleting Then select the option Add Column or Edit Column.
Column
Click on the Add… button.
This show you a Add Column dialog box. Where you can add the desired columns. In this
application we need five columns, with header as
•Salute – Mr., Mrs., Dr. etc.
•First Name
•Last Name
•Email ID
•Mobile Number.
Check the option Read Only,
Only so that content of cell (of the DataGridView) does not get
changed accidently.
The content of the DataGridView is unbounded, that means it is not bounded with any
data objects, like dataset, etc. So here we have to provide data rows during run time
through a function or subroutine.
Go to the property settings of DataGridView dg. Change the SelectionMode property as
FullRowSelect,
FullRowSelect so that when will click on any cell of the DataGridView then it will select the
whole row.
Change the AutoSizeColumnsMode property as Fill,
Fill so that the columns will adjust so as to
fill the DataGridView .
Now the DataGridView will look like as shown below. Now, to fill the DataGridView we
need some data, this data will be collected by use of a Class. So let us create a class.
Go to the Solution Explorer and Right click on the project. A context menu will appear.
Select Add Option from the menu, this will show another menu (its sub menu). From this
submenu select the option Class . This will create a class.

What is a Class?
A Class is like a mould (say mould of candle) by which you can make many candles as you
like. The candle made by a mould will look alike, like what the mould is intended to
produce. Each candle produced, is an Object.
Object

So a class is a mould and an object is a candle. Each candle (object) will have properties
inherited from its mould (class).
Object Oriented Programing relies on objects.

In.NET development an object is typically represented by a class, like a Form, a


Button, a TextBox etc.
etc

Structures are also objects but their purpose is to represent a value. They are not
meant for taking any actions. A Class have some members that enable taking
actions, known as methods. Field, Property are also part of a Class. Events are
handled by a class.

When we create an instance of a class in the form of Object, we make that object to
behave like the class want it to behave.

So if we create a TextBox1 from a TextBox Class , it will have all the properties of TextBox
Class, like Text,
Text Width etc. It will have Events like TextChanged,
TextChanged MouseEnter etc. Same
way it has some Methods like ToString,
ToString SelectAll etc.

In our example application we will use class to handle all the requisites.
The newly created class will look like as follows. I have named it as clsContacts.

Declaring Classes:

Classes support the following visibility modifiers: Public, Protected, Friend, Private and
Protected Friend. But only Public and Friend modifiers are allowed to declare a class.

Classes with Public can be reached from other assemblies. Classes with Friend visibility can
be reached from within the assembly that defines them.

Both modifiers are the only valid ones for non nested classes.
Fields:

Fields are the places in where you can store information and can read information from.
They are declared in the form of class level variables and differ from local variables in that
these are declared at the method or property level.

Here we have declared five fields as variables of string type. These have modifiers as Public
so that these can be accessed from outside of the class, like from Form9.vb

We will use these fields to pass on data from different forms.


To hold data for display and edit we will use Dialog Forms. So Right Click on the Solution
Explorer and add a New Item. Select a Dialog Form from the Templates. Name it as
dlgReadContacts.Vb and Add.
Change its Text Property to Contact Information so that its Title will be Contact Information.
Information
Design the Dialog Form as shown below with Five Labels, Four Text Boxes, and One
ComboBox. Name the objects as shown below:
•Combo Box as cmbSalute
•Text Boxes as txtFirstName, txtLastName, txtEmailID, txtMobileNo
Click on the Extender Button on the right side of the CmboBox and click on the Edit Items
hyperlink. This will help in assigning Options for the ComboBox , cmbSalute.
Add the options items and click OK button to save it.
Now let us use this Dialog box to display the fields of the class clsContacts. For this purpose
let us create a routine pReadValiable(). This is a method, which will get data from
dlgReadContacts and if DialogResult is OK then the fields of the class will have the values
collected from the dialog box.

In this way the fields will have its values. Since the method is a public so it can be accessed
from outside of the class, that is from Form9.
Now let us open our Form9.vb form and let us double click with our mouse on the form.
On double clicking with the mouse it will go to the code behind window as shown below.
Before going into the real application, let us use the class we have created. Let us create
another form named Form10.vb, and put a button. Create a method on click event of the
button. By double clicking it. Typed the following code.

The first line Dim cls As clsContacts, suggest that cls is a declaration and cls can have all the
properties and methods provided by clsContacts class. So if we try to run this application,
we will have an error of initialisation of an object.

Let me explain this, by having a mould I can make a candle but I do not have a candle. So by
the declaration, the compiler knows that there is a variable cls which can become an
object but still it is not an object. So it does not have any memory allocation. Therefore, we
can not make behave like an object from the class clsContacts. Then what to do?
So we will add another line of code, as
cls=New cslContacts

Here we are creating a new instance of the clsContacts as an object. Now object got its
existence.

So now if we run the form we will get appropriate result.


Now if we want to have a multiple instance of the class clsContacts, then we have to create
multiple instance as shown. Here we have created cls0, cls1, cls2 objects and then assigns
values to the fields to its respective objects. But this is a bit difficult to handle in an
application. So we would try to create an array of objects.

What is an Array?
An Array is a set of values of same type. So in Array you can store a set of items having
same nature (like integer, strings etc.). Arrays are reference types all deriving from the
System.Array class and can be both one-dimensional and multidimensional. So an array can
be a type of clsContacts. Here we will use an array named aContactList.
Here I have created an array of object type clsContacts, of size 50. Array numbering fro 0 to
49.
Now go to the design form Form9 and select the menu option Add a Contact by double
clicking it. This will create a routine as AddAContactToolStripMenuItem_Click to handle a
click event of the menu option. Add the following code. Let us run it first, then have
explanation.
Press F5 and Run the application. Select Menu Item Add a Contact.

An empty dialog box will appear feed


the data and press OK button, so as
to save the fields into the class
object aContactList(i) and add it to
the DataGridView as a new row.
How exactly it worked?
If you look into the code, in the top there are two declaration one is the array aContactList
and another is an integer nPointer.
nPointer The nPointer will help us to count the maximum number
of object has been instantiated or initialised.

In the method AddAContactToolStripMenuItem_Click , nPonter=nPointer+1 is used to


increment the nPointer by 1. At first it is -1 and after running it first time the value will be 0,
that is the first item of the array aContactList().

The line aContactList(nPointer) = New clsContacts is used to initialise the object. At first time
it is aContactList(0).
The line aContactList(nPointer).pReadContacts() is used to call the method from the class
pReadContacts. This invokes a dialog box dlgReadContacts, where desired data is filled.

The line dg.Rows.Add(.strSalute, .strFirstName, .strLastName, .strEmailID, .strMobileNo) is


used to add a row in the DataGridView dg.

In this way we can add as many rows as we can desire.

But there is a problem. While we enter first data , the combobox and textboxes appears as
blank, but when we add another contact, the old data is not washed away from the
combobox and textboxes.
So to avoid this let us add another method that will help in reinitialise the ComboBox and
TextBoxes. So I have addes another routine as pDisplayContacts() as shown below.
Now let us change the line aContactList(nPointer).pReadContacts() to
aContactList(nPointer).pDisplayContacts() as shown below. Run the application and will have
the desired result.
If we add the following code to the Click Event of the menu item Delete A Contact as shown
below, we will have a routine for deletion option.

In this procedure (routine), first it checks if any row is selected or not. If no row has been
selected then dg.SelectedRows.Count is equal to 0. If the value of dg.SelectedRows.Count is
0, then the control will be exited from the routine and nothing will happen.

If dg.SelectedRows.Count has a value other than 0, then program control goes to the line
Dim strNameTemp As String = dg.SelectedRows(0).Cells(1).Value
where a string strNameTemp is declared and assigned with a value from the second cell
[First Name] of the row selected.
The line
For i As Integer = 0 To nPointer
will be used to traverse through the array of objects aContactList, from the first.

The line
If aContactList(i).strFirstName = strNameTemp Then
will match if the desired value is in the object or not.

The line
dg.Rows.Remove(dg.SelectedRows(0))
if the desired object is found then first remove the row from the DataGridView dg.
dg

Then
For j As Integer = i + 1 To 49
aContactList(j - 1) = aContactList(j)
Next
traverse through the array of objects and assign the values of the succeeding object to the
preceding object. In this way the object to be removed will be overwritten by the succeeding
object.

This can be seen in the next page.


To edit any row from the DataGridView, we will add a routine which will handle the click
event generated by the menu item Edit a Contact . Same way as in the case of remove a
contact routine, first check if we have a row selected. If a row has been selected then
traverse through the array of objects and find out the object which have the desired data by
comparing the First Name with the variable strNameTemp.
strNameTemp After finding the proper object
the method pDisplayContacts will help to call the dialog box, where we can change the data.
After if we change the data it will be collected by the object.
Run the application and change what ever row you want.

As you have observed that we are unable to save the data, for further use. Whenever we run
the application we get an empty DataGridView. Therefore we have reenter all the required
data once again.

Let us save the data in the disk so that we can load the data whenever required.

We will create a File named Contacts.txt where we will save the data stored in the
DataGridView.
I have added two command buttons
cmdLoad – with a caption Load Contacts, will help to load data from the file from the disk.

cmdSave – with a caption Save Contacts, will help to save or write data on the disk . We will
use a stream.
stream
Before going further I need a class method which will help me in concatenating the set of
data an object held in its field. So I have created a Function named fConcatContacts().
fConcatContacts

This function returns a string with a separator ~ between each field. This separator will help
latter on in segregating the information.
What is Stream?
Streams are sequences of bytes, exchanged with some kind of sources, such as files,
memory, and network (System.Net.Sockets.NetworkStream Class).

A stream is represented by the abstract class System.IO.Stream. This class is a base class for
different kinds of streams and that implements the IDisposable interface.

The Stream class exposes some common members that you find in all other streams.

Visual Basic includes classes that make it relatively easy to manipulate


text files: StreamWriter and StreamReader

You create text files instantiating the StreamWriter class, which is a specific stream
implementation for writing to text files.

First you have add a Imports statement at the top of the Form9 Class as:
Imports System.IO
Then create a method for handling the cmdSave click event, as cmdSave_Click routine.

The line of code


Dim swContacts As New StreamWriter("Contacts.txt", False, System.Text.Encoding.UTF8)
create an instance of an object swContacts from a StreamWriter class which takes the
name of the file as a parameter.
The second parameter suggests that the file should append the data or overwrite the whole
file. By putting False as a parameter, it will not append the data in the file, but will
overwrite.

It will traverse through all the objects till there is no data or a nothing is found.

The method WriteLine of the StreamWiter class helps in writing the data into the said text
file in the disk.

The function fConcatContacts helps in concatenate the fields with data from the object.

In this way a file with name Contacts.txt is written in the disk.


Now run the application and enter data as you wish. Then click on the save button. It will
save the data in a file named Contacts.txt in the disk and give a message as saved.
But where is the file Contacts.txt?
Contacts.txt

Since the program runs after building an Executing file of the same name as of the
Application, so you can find the Contacts.txt file where the EXE is placed.

Normally it is in the bin directory. You can find it by a number of ways. One way is to click on
the option Show All Files,
Files as shown below.
The file is in the Debug Folder of the Bin Folder. Double click the Contacts.txt File so as to
open it.
Here you can see the data saved in the text file Contacts.txt.

It’s Cool.
To load the data in the DataGridView, I need another class which will split the concatenated
data from the file. So I have created a method which will split or segregate the data.

The line
Dim result() As String = strLine.Split("~"c)
create an array of string result, with five data field. By traversing through the whole array
different values of the field are captured. This is returned to the object aContactList.
By using ReadLine method of the StreamReader class each line is read from the Contacts.txt
file.

The StreamReader read the whole file till it go past the end of the file, where it returns
nothing.
Run the application and click the button Load Contacts. You can see the data from the text
file Contacts.txt is loaded in the DataGridView.
Now if we could write and read data into a text file then we can write any type of text file
and read data from it. Let us write a file with HTML tags and naming it as a HTM as extention
and then read it into an internet explorer.

I have created a routine which will handle the click event of menu item Report.
Report This will
create a HTML file at C drive with a name Try.html.
Run the application. Click the menu option Report. It will create a file and say Saved!!!.
If we browse this file in the internet explorer, we will see the following.

So far so good. But we want our own browser built into our application. For that purpose let
us create our own web browser in the Form10.vb.
On the Form10 drag and place a WebBrowser Tool from Toolbox. Le it arrange it self as dock
in the parent container.
Name this WebBrowser object as wb.
wb
I have added two more lines of code.
Form10.wb.Navigate(“C:\Try.html")
Form10.Show()
these lines will direct the WebBrowser object to navigate to the web page Try.html and by
showing this form we will see the created web page into our web browser.
Now let us create a template for our report. I have used Microsoft Front Page, to create a
template report as shown in the next page.
On Viewing its source code. I copied its html tags into a Notepad.
Since I am going to write it by using a stream writer, therefore, I have replaced all the double
quotes with single quotes.
Then written the writeline methods as shown below.
Pasted the codes from the note pad to the routine ReportToolStripMenu_Click.
Run the application.
Click on the Load Contacts button
Click on the Report menu option.
My web browser will appear with a list of contacts as shown below.
That’s all

In the next presentation we will talk about


the stream and will make an application
based on the different streams.

The matter contained in this presentation is nothing to do with my employer.

Вам также может понравиться