Chapter Two
Chapter Two
Chapter Two
Introduction to .NET
Microsoft .NET Framework
The Microsoft.NET Framework is the new computing platform from Microsoft designed to
simplify the development for distributed environment such as the Internet.
The framework is designed from the grounds up with the Internet in mind.
It is not that this Framework was designed for Internet programming only, but simply that if
an application you create needs Internet capabilities, access to those capabilities are available
and almost transparent.
The .NET Framework is composed of two main components shown in the figured below:
1|Page
In addition it provides programmers with services for memory management, data
types, security etc.
2. .NET Framework Class Library.
A collection of ready-made reusable classes that work with the CLR.
Programmers using any of the .NET programming languages can use these classes to
include in their applications.
The CLR Allows programmers to write code in different Microsoft languages of their
choice, and ensure that the parts can work together
Examples of the classes provided by the library are:
Database access and manipulation
User Interface – Windows Forms, Web Forms, Web Services
Security
Encryption and decryption
.NET is the framework for which we develop applications. It sits in between our
application programs and operating system. Applications developed for .NET run
inside .NET and are controlled by .NET. It supports both Windows and web applications.
.NET provides an object oriented environment. It ensures safe execution of the code by
performing required runtime validations. For example, it is never possible to access an
element of an array outside the boundary. Similarly, it is not possible to a program to
write into another programs area, etc. The runtime validations performed by .NET makes
the entire environment robust.
2|Page
The following are different types of applications that can make use of .NET class library.
1. Console applications.
2. Windows GUI applications.
3. ASP.NET applications – web applications.
4. XML Web services.
5. Windows services.
Some of the types of applications:
Console Application – Usually Text only application. Runs from a DOS or
COMMAND PROMPT screen.
Windows Application – Graphical Interface user application. Typical Windows
application that you normally use, such as MS WORD etc.
Web Based Windows Application – Web application that uses a Browser such as
Internet Explorer.
1. Console Application
A Console Application is a program whose output is usually text based (No Graphics).
Console Applications usually do not contain Forms or any graphics, but they can. You
can if you like from a console application call Windows Forms etc.
Console Applications are created when an application performs processing that
requires very or no user interaction.
They are lighter and have less overhead than standard windows applications since
they contain no graphical libraries etc.
Console applications are a good choice when creating programs such as login scripts,
device drivers, backend processes, test programs, programs that control hardware
devices etc.
The results of a Console Application is placed or controlled from a Command
Prompt Window:
2. Windows Application
Windows Applications are your standard graphical applications we are using.
Windows Apps use graphical entities such as Forms, Web Forms etc.
3. Web-Based Application
These are applications created for the World-Wide-Web or Internet.
3|Page
These applications run from a Browser, but the actual program code for these
applications (HTML) reside on a Web Server and are distributed to any client or
browser which makes the request.
Visual Basic Standard Modules
A module is a global or public object where you can place program code such as variables,
functions & procedures that can be seen by all code in the entire project.
The Module has the following characteristics:
Modules contain a method named Sub Main() that can be used as the starting point of
the application. Note this applies to both Console Applications and Windows
Applications.
Modules contain variable declarations, functions & procedures or source code
ONLY! No forms!
Modules are a good place to put program code that may be common to several forms
or other modules.
Modules contain variables & Methods.
Modules are like forms but without the visual!
4|Page
Programming Errors
There are three varieties of programming errors:
Syntax Errors – Errors generated due to the code not following the rules of the language
These errors usually involve improper punctuation, spelling or format
These problems are easier to solve since the compiler identifies the erroneous
statement and you just have to review the rules of the language to make sure you are
writing the statement properly
Run Time Errors – Program halts during execution. The program passed the syntax test but
fails during execution. .
These problems are usually caused by improper arithmetic execution, attempting to
access recourses that are not available etc
These problems are difficult to solve since they only show up when the program
runs.
Logical Error – The program is not doing what is supposed to do. .
The algorithm fails to solve the problem the program was written to resolve
These problems are even more difficult to solve since you need to re-think and go
back to the planning phase and review the Algorithm.
When programming using Visual Basic Objects & environment there are two aspects to keep
in mind:
Visible Graphical Aspect – Most Visual Basic Objects & Controls have a Graphical
representation. In other word the Object has a visible part. For example in the Toolbox there
is a graphical element for a Command Button, Label, Text Box etc.
Invisible Aspect – The invisible aspect is the part of the Object where you write the code in.
This involves double-clicking on the object and invoking the Code Editor Screen.
5|Page
Common Properties
In order to make VB easier to learn, Microsoft gave most of the controls and objects similar
properties
For examples, most controls have the following properties:
Name The string value used to refer to the control in code.
Caption The text that is displayed in the label
Text The string of text that is to be displayed in the control.
ForeColor Specifies the color of text or graphics to be displayed in the control.
BackColor Specifies the background color of the control.
Font For controls displaying text, specifies the font (name, style, size, etc.) to be
applied to the displayed text.
Picture Specifies the graphic to be displayed in the control.
Visible Specifies whether the control is visible or hidden.
Enabled Determines whether or not the control can respond to user-generated events.
Width Specifies the width of the control in pixels.
Height Specifies the height of the control in pixels.
6|Page
Properties define the characteristics of an object such as Size, Color etc. or sometimes the
way in which it behaves. For example, a TextBox accepts properties such as Enabled, Font,
MultiLine, Text, Visible, Width, etc.
The properties that are discussed above are design-time properties that can be set at the
design time by selecting the Properties Window. But certain properties cannot be set at
design time. For example, the CurrentX and CurrentY properties of a Form cannot be set at
the design time.
A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. A complete
definition of cat must only encompass on its looks, but should also include a complete
itemization of its activities. Therefore, a cat's methods might be move, jump, play, breath etc.
Similarly in object-oriented programming, a method is a connected or built-in procedure, a
block of code that can be invoked to impart some action on a particular object. A method
requires an object to provide them with a context. For example, the word Move has no
meaning in Visual Basic, but the statement,
Text1.Move 700, 400 performs a very precise action. The TextBox control has other
associated methods such as Refresh, SetFocus, etc.
7|Page
As explained above, several events are associated with different controls and forms, some of
the events being common to most of them and few being specific to each control.
VB controls
1) Label
Label controls to provide a descriptive caption and possibly an associated hot key for other
controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption property.
In most cases, you just place a Label control where you need it, set its Caption property to a
suitable string (embedding an ampersand character in front of the hot key you want to
assign), and you're done. Caption is the default property for Label controls.
Other useful properties are BorderStyle(if you want the Label control to appear inside a 3D
border) and Alignment (if you want to align the caption to the right or center it on the
control). In most cases, the alignment depends on how the Label control relates to its
companion control: for example, if the Label control is placed to the left of its companion
field, you might want to set its Alignment property to 1-Right Justify. The value 2- Center is
especially useful for stand-alone Label controls.
You can insert a literal & character in a Label control's Caption property by doubling it. For
example, to see Research & Development you have to type &Research && Development.
Note that if you have multiple but isolated &s, the one that selects the hot key is the last one
and all others are ignored. This tip applies to all the controls that expose a Caption property.
(The & has no special meaning in forms' Caption properties, however.)
If the caption string is a long one, you might want to set the Label's WordWrap property to
True so that it will extend for multiple lines instead of being truncated by the right border of
the control. Alternatively, you might decide to set the AutoSize property to True and let the
control automatically resize itself to accommodate longer caption strings.
You sometimes need to modify the default value of a Label's BackStyle property. Label
controls usually cover what's already on the form's surface (other lightweight controls, output
from graphic methods, and so on) because their background is considered to be opaque. If
you want to show a character string somewhere on the form but at the same time you don't
want to obscure underlying objects, set the BackStyle property to 0- Transparent.
2) TextBox
TextBox controls offer a natural way for users to enter a value in your program. For this
reason, they tend to be the most frequently used controls in the majority of Windows
applications. TextBox controls, which have a great many properties and events, are also
among the most complex intrinsic controls.
8|Page
Setting properties to a TextBox
Text can be entered into the text box by assigning the necessary string to the text
property of the control
If the user needs to display multiple lines of text in a TextBox, set the MultiLine
property to True
To customize the scroll bar combination on a TextBox, set the ScrollBars property.
Scroll bars will always appear on the TextBox when it's MultiLine property is set to
True and its ScrollBars property is set to anything except None(0)
If you set the MultilIne property to True, you can set the alignment using the
Alignment property. The test is left-justified by default. If the MultiLine property is
set to False, then setting the Alignment property has no effect.
Run-Time Properties of a TextBox control
The Text property is the one you'll reference most often in code, and conveniently it's the
default property for the TextBox control. Three other frequently used properties are these:
The SelStart property sets or returns the position of the blinking caret (the insertion point
where the text you type appears). Note that the blinking cursor inside TextBox and other
controls is named caret, to distinguish it from the cursor (which is implicitly the mouse
cursor). When the caret is at the beginning of the contents of the TextBox control, SelStart
returns 0; when it's at the end of the string typed by the user, SelStart returns the value
Len(Text). You can modify the SelStart property to programmatically move the caret.
The SelLength property returns the number of characters in the portion of text that has been
highlighted by the user, or it returns 0 if there's no highlighted text. You can assign a nonzero
value to this property to programmatically select text from code. Interestingly, you can assign
to this property a value larger than the current text's length without raising a run-time error.
The SelText property sets or returns the portion of the text that's currently selected, or it
returns an empty string if no text is highlighted. Use it to directly retrieve the highlighted text
without having to query Text, SelStart, and SelLength properties. What's even more
interesting is that you can assign a new value to this property, thus replacing the current
selection with your own. If no text is currently selected, your string is simply inserted at the
current caret position.
The following Figure summarizes the common TextBox control's properties and methods.
9|Page
3) PictureBox Control
PictureBox controls are among the most powerful and complex items in the Visual Basic
Toolbox window. In a sense, these controls are more similar to forms than to other controls.
For example, PictureBox controls support all the properties related to graphic output,
including AutoRedraw, ClipControls, HasDC, FontTransparent, CurrentX, CurrentY, and all
the Draw, Fill, and Scale properties. PictureBox controls also support all graphic methods,
such as Cls, PSet, Point, Line, and Circle and conversion methods, such as ScaleX, ScaleY,
TextWidth, and TextHeight.
Loading images
Once you place a PictureBox on a form, you might want to load an image in it, which you do
by setting the Picture property in the Properties window. You can load images in many
different graphic formats, including bitmaps (BMP), device independent bitmaps (DIB),
metafiles (WMF), enhanced metafiles (EMF), GIF and
JPEG compressed files, and icons (ICO and CUR). You can decide whether a control should
display a border, resetting the BorderStyle to 0-None if necessary. Another property that
comes handy in this phase is AutoSize:
Set it to True and let the control automatically resize itself to fit the assigned image.
You might want to set the Align property of a PictureBox control to something other than the
0-None value. By doing that, you attach the control to one of the four form borders and have
Visual Basic automatically move and resize the PictureBox control when the form is resized.
PictureBox controls expose a Resize event, so you can trap it if you need to move and resize
10 | P a g e
its child controls too. You can do more interesting things at run time. To begin with, you can
programmatically load any image in the control using the LoadPicture function:
Picture1.Picture = LoadPicture("c:\windows\setup.bmp")
4) Frame controls
Frame controls are similar to Label controls in that they can serve as captions for those
controls that don't have their own. Moreover, Frame controls can also (and often do) behave
as containers and host other controls. In most cases, you only need to drop a Frame control on
a form and set its Caption property. If you want to create a borderless frame, you can set its
BorderStyle property to 0-None.
Controls that are contained in the Frame control are said to be child controls. Moving a
control at design time over a Frame control—or over any other container, for that matter—
doesn't automatically make that control a child of the Frame control. After you create a
Frame control, you can create a child control by selecting the child control's icon in the
Toolbox and drawing a new instance inside the Frame's border. Alternatively, to make an
existing control a child of a Frame control, you must select the control, press Ctrl+X to cut it
to the Clipboard, select the Frame control, and press Ctrl+V to paste the control inside the
Frame. If you don't follow this procedure and you simply move the control over the Frame,
the two controls remain completely independent of each other, even if the other control
appears in front of the Frame control.
Frame controls, like all container controls, have two interesting features. If you move a
Frame control, all the child controls go with it. If you make a container control disabled or
invisible, all its child controls also become disabled or invisible. You can exploit these
features to quickly change the state of a group of related controls.
5) Command Control
Using Command Button controls is trivial. In most cases, you just draw the control on the
form's surface, set its Caption property to a suitable string (adding an & character to associate
a hot key with the control if you so choose), and you're finished, at least with user-interface
issues. To make the button functional, you write code in its Click event procedure, as in this
fragment:
Private Sub Command1_Click()
' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
11 | P a g e
End Sub
You can use two other properties at design time to modify the behavior of a Command
Button control. You can set the Default property to True if it's the default push button for the
form (the button that receives a click when the user presses the Enter key—usually the OK or
Save button). Similarly, you can set the Cancel property to
True if you want to associate the button with the Escape key.
The only relevant Command Button's run-time property is Value, which sets or returns the
state of the control
(True if pressed, False otherwise). Value is also the default property for this type of control.
In most cases, you don't need to query this property because if you're inside a button's Click
event you can be sure that the button is being activated. The Value property is useful only for
programmatically clicking a button:
This fires the button's Click event.
Command1.Value = True
6) OptionButton
OptionButton controls are also known as radio buttons because of their shape. You always
use OptionButton controls in a group of two or more because their purpose is to offer a
number of mutually exclusive choices.
Anytime you click on a button in the group, it switches to a selected state and all the other
controls in the group become unselected.
Preliminary operations for an OptionButton control are similar to those already described for
CheckBox controls. You set an OptionButton control's Caption property to a meaningful
string, and if you want you can change its Alignment property to make the control right
aligned. If the control is the one in its group that's in the selected state, you also set its
12 | P a g e
Valueproperty to True. (The OptionButton's Value property is a Boolean value because only
two states are possible.) Value is the default property for this control.
In the following example, the shape control is placed in the form together with 3 Option
Boxes. When the user clicks on different option boxes, different shapes will appear. The
values of the shape control are 0, 1, and 2 which will make it appear as a rectangle, a square,
an oval shape, respectively.
7) Check Box Control
The CheckBox control is similar to the option button, except that a list of choices can be
made using check boxes where you cannot choose more than one selection using an
OptionButton. By ticking theCheckBox the value is set to True. This control can also be
grayed when the state of the CheckBox is unavailable, but you must manage that state
through code.
When you place a CheckBox control on a form, all you have to do, usually, is set its Caption
property to a descriptive string. You might sometimes want to move the little check box to
the right of its caption, which you do by setting the Alignment property to 1-Right Justify, but
in most cases the default setting is OK. If you want to display the control in a checked state,
you set its Value property to 1-Checked right in the Properties window, and you set a grayed
state with 2-Grayed.
The only important event for CheckBox controls is the Click event, which fires when either
the user or the code changes the state of the control. In many cases, you don't need to write
code to handle this event. Instead, you just query the control's Value property when your code
needs to process user choices. You usually write code in
a CheckBox control's Click event when it affects the state of other controls.
Example
Private Sub Command1_Click()
If Check1.Value = 1 And Check2.Value = 0 Then
MsgBox "Apple is selected"
ElseIf Check2.Value = 1 And Check1.Value = 0 Then
MsgBox "Orange is selected"
Else
MsgBox "All are selected"
End If
End Sub
13 | P a g e
8) Combo Box
ComboBox controls present a set of choices that are displayed vertically in a column. If the
number of items exceed the value that be displayed, scroll bars will automatically appear on
the control. These scroll bars can be scrolled up and down or left to right through the list.
The following Fig lists some of the common ComboBox properties and methods.
9) List Box
The function of the List Box is to present a list of items where the user can click and select
the items from the list. In order to add items to the list, we can use the AddItem method. For
example, if you wish to add a number of items to list box 1, you can key in the following
statements
Example
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
14 | P a g e
The items in the list box can be identified by the ListIndex property, the value of the
ListIndex for the first item is 0, the second item has a ListIndex 1, and the second item has a
ListIndex 2 and so on
MDI (multi-document interface) - allows users to simultaneously view multiple
documents. SDI (single-document interface) - unlike MDI, SDI only supports a single
“active” document.
15 | P a g e