VB Notes
VB Notes
1/119
LECTURE 1
Introduction to VB. (Visual Basic)
Visual basic is a Microsoft Product. Visual basic is indisputably the most
attractive development environment currently available. Visual basic is an ideal
programming language for developing sophisticated professional applications
for Microsoft windows. It makes use of graphical uses interface for crating
robust and powerful applications.
Visual basic is a much-enhanced version of the Basic Programming Language
and the basic Integrated Development Environment (IDE). It acts as front-end
tool for developing applications with databases (FoxPro, oracle, SQLServices) as
back end.
How to Invoke VB
After installing Visual Basic on your system, you start it from the Windows Start
menu. The exact details will depend on how you got Visual Basic, which is
available both as a standalone product and as part of Microsofts Visual Studio
development platform. In any case, the process will be as follows:
Basic
and
1).
select
a
your
Introduction to
Environment)
VBIDE
(Integrated
Development
Main Window
The main Visual Basic window serves two primary purposes. First, it contains the
other windows that the program displays. Second, it displays the menu bar and
toolbar along the top of the window. The menu bar contains the titles of Visual
Basics menus, which contain the programs commands. The toolbar displays
buttons you can click on to carry out commonly needed commands. Note that if
you position the mouse pointer over a toolbar button for a moment (dont click),
Visual Basic will display a brief description, called a tool tip, of the buttons
function.
3/119
Properties Window
Below the Project Explorer window is the Properties window. This window lists
the properties of the currently selected object, the name of which is displayed in
the box at the top of the window. A form is an object, and the controls you place
on it are also objects. An objects properties control its appearance and
behaviorfor example, the color of a forms background is one of its properties.
Youll be learning a lot about object properties throughout this book, so I wont
go into any further detail right now.
Toolbox Window
On the left side of the screen is the toolbox. This window contains icons
representing the various visual objects, or controls, that you can place on a
Visual Basic form. To place a control, click on the corresponding toolbox button,
then point and drag on the form to specify the size and location of the control.
In the lower right corner of the Visual Basic screen is the Form Layout window.
It shows a miniature representation of a computer screen with a small icon
showing the relative size and position of each of your projects forms. You use
the Form Layout window to view the relationships among your programs forms.
If you point at a form icon and drag it to a new location, youll change the
screen position where the form initially displays during program execution.
The Immediate window lets you enter a Visual Basic command or
expression and see its result using the Print command (which can also be
shortened to ?). In break modethat is, when you have temporarily suspended
a running programyou can use these commands to display the current value
of a variable or an expression. You can also write diagnostic messages from
your application's code to this window using the Debug.Print statement. Because
the Immediate window isn't visible when the application is compiled and
executed outside the environment, such diagnostic statements aren't included in
the executable file. You can quickly open the Immediate window by pressing the
Ctrl+G key combination
The Locals window is active only when a program is executing. It lists the
values of all the variables that are local to a module or to a procedure. If the
variable is an object itself (a form or a control, for example) a plus (+) sign
The Watches window has a dual purpose: it lets you continuously monitor
the value of a variable or an expression in your programincluding a global
variable, which is outside the capabilities of the Locals windowand it also gives
you the ability to stop the execution of a program when a given expression
becomes True or whenever it changes its value. You can add one or more watch
expressions using the Add Watch command from the Debug menu, or you can
select the Add Watch command from the pop-up menu that appears when you
right-click the Watches window itself.
The Color Palette window is handy for quickly assigning a color to an
object, such as the control that's currently selected on a form designer. You can
select the foreground color of an object by left-clicking on the desired color, and
if you click on an empty item in the bottom row of cells you can also define a
custom color. Finally, you can select the background color of an object if you
click on the larger square located near the upper left corner of the Color Palette
window.
Methods
Other Windows
Visual Basic has a number of other windows you will use during program
development. They are not shown in Figure 2.2 because Visual Basic displays
these windows only when you need them. For the most part, well deal with
these other windows as the need arises. One type of window, however, is so
central to Visual Basic programming that Ill take a moment to introduce it now.
In a code window, you enter and edit Basic code. It works pretty much like any
other Windows text editor: You can type text, delete it, move and copy it from
place to place, and so on. If you want to see what a code window looks like,
click on the View Code button in the Project Explorer window. An empty code
window will open.
Properties
Each Visual Basic object has properties that determine its behavior and, if the
object has a visual interface, appearance. For example, almost all visible objects
Most Visual Basic objects have one or more methods associated with them. A
method can be thought of as a chunk of code that does something to, or with,
the object. Instead of you having to write the code, however, it is an integral
part of the object.
The methods that are available differ from object to object. For example, the
Move method, which moves an object to a different location on screen, is
available for most objects. In contrast, the Print method, which displays text on
an object, is available only for forms and a few other objects where the display
of text makes sense.
Event Procedures
Earlier in this chapter, I mentioned that Visual Basic brought two
groundbreaking innovations to Windows programming. The first one was visual
interface design. Now well meet the second one: event detection. Well, not
event detection itself; thats nothing new. The real innovation is the ease with
LECTURE 2
VB Project: - VB Project is a group of all the files that make up our program.
These might include forms, modules, graphics or Active-X controls each of which
is saved as an individual file.
File Type Description
.FRM
Form
.BAS
Module
.FRX
Automatically generated file for every graphic in your object.
.OCX
Active -X control
.VBP
Visual Basic Project.
Back End - Front End:
Front End: The interface, which provides the interactivities with application to
user, is called fronted. Tools used for fronted are: - VB, VB.net, Developers
2000 etc.
Back End: The code which response every user actions as stores data is
particular manner, which is inputted by user using fronted, is called backend.
Back end packages are: - Database Management system (oracle, SQLServer,
Informix, Access)
8/119
Introduction to Controls
The controls are the building blocks on which we assemble the VB program. The
toolbox is a palette of controls from which we can select controls and place them
in our forms. There are two types of Controls in VB.
Intrinsic Controls:
In Microsoft Visual Basic jargon, intrinsic controls (or built-in controls) are those
controls visible in the Toolbox window when you launch the environment. This
important group includes controls, such as Label, TFextbox, and
CommandButton controls, that are used in nearly every application. As you
know, Visual Basic can be extended using additional Microsoft ActiveX Controls
(formerly known as OCX controls, or OLE custom controls) either provided in the
Visual Basic package or available as commercial, shareware, or even freeware
third-party products
Extrinsic Controls
These controls we have to add these from the components windows by selecting
it from the project menu. These controls are the files having, OCX extension.
Intrinsic Controls
Controls
Pointer
Prefix Description
-Selects controls.
Label
lbl
Frame
Frm
Check Box
chk
Combo Box
cbo
Hscroll Box
hsb
add a new
controls.
option.
item.
real
Dir
Shape
shp
folder.
Image
Img
Picture Box
Pic
container.
Text Box
Txt
edit text
Options Button
Opt
List Box
Lst
Vscroll Bar
vsb
Drv
fil
Line
Lin
Data
Dat
Extrinsic Controls
Rich Text Box Common Dialog Control Microsoft Windows Common
Control
Microsoft ActiveX Data Control Microsoft Flex Grid Control etc.,
LECTURE 3
The Form Object
After this long introductory description of properties, methods, and events that
are common to most Visual Basic objects, it's time to see the particular features
of all of them individually. The most important visible object is undoubtedly the
Form object because you can't display any control without a parent Form.
Conversely, you can write some moderately useful applications using only forms
that have no controls on them. In this section, I'll show a number of examples
that are centered on forms' singular features.
Properties:
Name: The name property is very important property in VB. This is the
name of the control that VB refers to when the program runs. In order to
know exactly what your forms are you should give them a descriptive
name and prefix it with letters form.
Back Color: The Back Color property sets the background color of the
form.
Border Style: The Border Style property determines how the border of a
form behaves. A form can have fixed borders that cannot be stretched or
resizable borders that can be stretched by dragging them with name.
12/
12/119
What happens after the Initialize event depends on how you referenced the form
in your code. If you referenced only one of its public variables (or, more
correctly, its Public properties), as in the following line of code,
The Resize event also fires when the user resizes the form manually and when
you programmatically alter the form's size.
Soon after the first Resize event comes the Activate event. This event also fires
whenever the form becomes the active form in the current application but not if
it loses and then regains the focus because the user switched to another
application. The Activate event is most useful when you need to update the
form's contents with data that might have been modified in another form. When
the focus returns to the current form, you refresh its fields:
nothing else happens and execution flow goes back to the caller. Your code is
now able to set the CustomerName variable/property to the new value because
in the meantime Visual Basic has created a new instance of the frmCustomer
object. On the other hand, if your code had referenced a form's own property or
a control on the form itself, Visual Basic can't complete the operation until it
actually creates the window and its child controls. When this step is completed,
a Load event is fired:
13/
13/119
txtTotalOrders.Text = gloTotalOrders
...
End Sub
14/
14/119
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. In
this section, I guide you through the most useful properties of TextBox controls
and show how to solve some of the problems that you're likely to encounter.
After you place a TextBox control on a form, you must set a few basic
properties. The first thing I do as soon as I create a new TextBox control is clear
its Textproperty. If this is a multiline field, I also set the MultiLineproperty to
True.
You can set the Alignment property of TextBox controls to left align, right align,
or center the contents of the control. Right-aligned TextBox controls are
especially useful when you're displaying numeric values. But you should be
aware of the following quirk: while this property always works correctly when
the Multiline property is set to True, it works with single-line controls only under
Microsoft Windows 98, Microsoft Windows NT 4 with Service Pack 3, or later
versions. Under previous versions of Windows 9x or Windows NT, no error is
raised but single-line TextBox controls ignore the Alignment property and always
align their contents to the left.
15/
15/119
16/
16/119
Run-Time Properties
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.
Label
Most people use 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. Be careful to
set the Label's TabIndex property so that it's 1 minus the TabIndex property of
the companion control.
Properties:
Command Button
Using CommandButton 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
End Sub
You can use two other properties at design time to modify the behavior of a
CommandButton 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 keyusually the OK or Save button). Similarly, you can set
Properties:
Name: This name is used by your code and visual basic to distinguish it
from the rest of controls.
Caption: Displays the text on the button.
Enabled: It has two values True/False, whether the button is in working
at run time or not.
Visible: Sets the visibilities to true/false.
Picture: Allows the user to set a picture for the button.
Events:
Click: invoked on mouse click
GotFocus: This event is generated when the button gets the to us.
LostFocus: Generated when the control lost the focus.
Hot Key
To give the user keyboard access to a control, insert an ampersand (&) before a
letter in caption property. At run time, this letter is underlined (the ampersand
is not visible), and the user can access the command by pressing ALT and the
letter. If you need an ampersand to show in the caption, put two consecutive
ampersands in the caption.
LECTURE 4
Variable
A variable is a name that references an area of memory, which holds a
temporary value. This value can change while an application is running.
Declaring Variables
In VB there are two types of declaration
Implicit Declaration: It is a default declaration there is no need to
declare variables before its used.
Explicit Declaration: This means that we must use a statement to
declare a variable. These statements describe the scope of the variable.
DIM variablename AS datatype
Naming Variables
Global Variables
In Visual Basic jargon, global variables are those variables declared using the
Public keyword in BAS modules. Conceptually, these variables are the simplest
of the group because they survive for the life of the application and their scope
is the entire application. (In other words, they can be read and modified from
anywhere in the current program.) The following code snippet shows the
declaration of a global variable:
' In a BAS module
Public InvoiceCount as Long
Module-Level Variables
If you declare a variable using a Private or a Dim statement in the declaration
section of a modulea standard BAS module, a form module, a class module,
and so onyou're creating a private module-level variable. Such variables are
visible only from within the module they belong to and can't be accessed from
the outside. In general, these variables are useful for sharing data among
procedures in the same module:
' In the declarative section of any module
Private LoginTime As Date
' A private module-level variable
Dim LoginPassword As String ' Another private module-level variable
You can also use the Public attribute for module-level variables, for all module
types except BAS modules. (Public variables in BAS modules are global
Sub PrintInvoice()
Static InProgress As Boolean
...
End Sub
Alternatively, you can declare the entire procedure to be Static, in which case all
variables declared inside it are considered to be Static:
You can access a module property as a regular variable from inside the module
and as a custom property from the outside:
Each time the procedure is executed, a local dynamic variable is re-created and
initialized to its default value (0, an empty string, or Nothing). When the
procedure is exited, the memory on the stack allocated by Visual Basic for the
variable is released. Local variables make it possible to reuse code at the
procedure level. If a procedure references only its parameters and its local
variables (it relies on neither global nor module-level variables), it can be cut
from one application and pasted into another without any dependency problem.
20/
20/119
' This is a Static local variable.
Static local variables are similar to private module-level variables, to the extent
that you can move a Static declaration from inside a procedure to the
declaration section of the module (you only need to convert Static to Dim,
because Static isn't allowed outside procedures), and the procedure will
continue to work as before. In general, you can't always do the opposite:
Changing a module-level variable into a Static procedure-level variable works if
that variable is referenced only inside that procedure. In a sense, a Static local
variable is a module-level variable that doesn't need to be shared with other
procedures. By keeping the variable declaration inside the procedure
boundaries, you can reuse the procedure's code more easily.
Static variables are often useful in preventing the procedure from being
accidentally reentered. This is frequently necessary for event procedures, as
when, for example, you don't want to process user clicks of the same button
until the previous click has been served, as shown in the code below.
Private Sub cmdSearch_Click()
Static InProgress As Boolean
' Exit if there is a call in progress.
If InProgress Then MsgBox "Sorry, try again later": Exit Sub
InProgress = True
' Do your search here.
...
' Then reenable calls before exiting.
InProgress = False
End Sub
Date variables can hold any date between January 1, 100, through December
31, 9999, as well as any time value. They take 8 bytes, exactly like Double
variables. This isn't a casual resemblance because internally these date/time
values are stored as floating-point numbers, in which the integer part stores the
date information and the decimal part stores the time information. (For
example, 0.5 means 12 A.M., 0.75 means 6 P.M., and so on.) Once you know
how Date variables store their values, you can perform many meaningful math
operations on them. For example, you can truncate date or time information
using the Int function, as follows:
MyVar = Now
' MyVar is a Date variable.
DateVar = Int(MyVar)
' Extract date information.
TimeVar = MyVar - Int(MyVar) ' Extract time information.
You can also add and subtract dates, as you would do with numbers:
MyVar = MyVar + 7
MyVar = MyVar - 365
Function
Cbool
Cbyte
Cdate
Cint
CLng
CSng
CStr
Cvar
Ccur
Operators
Arithmetic Operators
The arithmetic operators perform mathematical manipulations. There are seven
of them. The first four, listed in Table 4.3, are the common operations that Im
sure you are familiar with.
String Manipulation
The only operator that works with string data is called the concatenation
operator, represented by the symbol &. Concatenation simply means to tack one
string onto the end of another. For example, if MyString is a string variable,
then executing the statement
MyString = Visual & Basic
results in the string Visual Basic being stored in the variable. You can also use
the + symbol for string concatenation. It is provided for compatibility with old
Basic programs, but its best to stick with & for new programs.
Table 4.3 Arithmetic operators.
Operation
Addition
Subtraction
Multiplication
Division
Symbol
+
*
Example
2+5
18 - 10
2*5
Result
7
8
10
Operator Precedence
What happens if an expression contains more than one operator? What
difference does it make? An example will illustrate. Consider this expression:
5+3*2
What does it evaluate to? If we perform the addition first, it evaluates to 16 (5
+ 3 = 8, 8 * 2 = 16); but if we perform the multiplication first, the result is 11
(3 * 2 = 6, 5 + 6 = 11). Which is correct? Because of such potentially
ambiguous expressions, Visual Basic includes strict rules of operator
Precedence
1
2
3
4
5
6
28/
28/119
Comparison Operators
Visual Basic provides a number of operators you can use to construct logical
expressions by asking questions about the data in your programs. Specifically,
these comparison operators perform comparisons between expressions,
returning a value of True or False, depending on the result of the comparison.
Table 4.5 lists the comparison operators.
We can see that if X is equal to 10 and Y is equal to 5, then the expression X <
Y will evaluate as False and X <> Y will evaluate as True. Assuming both Q and
Z have been declared as type Integer, we can use the numerical value of a
logical expression like this
Q=X<Y
Z = X <> Y
which would result in the variable Q having the value 0 and Z having the value 1. More often, however, logical expressions are used in program control, as
youll see soon. But first, we need to take a look at how to combine two or more
logical expressions to arrive at a single True/False answer.
Comparison
Equal to
Greater than
<
>=
Less than
X
Greater than or X
equal to
Less than or equal X
to
Not equal to
X
<=
<>
Example
X=Y
X>Y
<Y
>= Y
<= Y
<> Y
Meaning
Is X equal to Y?
Is X greater than
Y?
Is X less than Y?
Is X greater than or
equal to Y?
Is X less than or
equal to Y?
Is X not equal to Y?
Logical Operators
The logical operators work to combine two or more logical expressions into a
single True or False answer. Why would we want to do this? Heres an example
from everyday life. You receive a call inviting you to join a group of friends for
dinner. If Mary is coming along, youd like to go, because youre a bit sweet on
her; otherwise, youll pass. This is a single logical condition, and easy to
understand. Now, assume for a moment that you also like Helen; if shes
coming with the group, youd also like to go. But if both Mary and Helen are
coming, the situation will get a bit too complicated, so you again will pass. In
Example
X And Y
Or
X Or Y
X Xor Y
Eqv (Equivalence)
X Eqv Y
Imp (Implication)
X Imp Y
Not
Not X
Evaluation
True if both X and Y are True;
False otherwise
True if X or Y, or both of them,
are True; False only if both X
and Y are False
True if X and Y are different
(one True and the other False);
False if both are True or both
are False
True if X and Y are the same
(both True or both False); False
otherwise
False only if X is True and Y is
False; True otherwise
True if X is False, False if X is
True
Of course, you can use the comparison and logical operators to ask questions
about object properties, too. Lets say you have two Check Box controls on a
form and want to determine if one or both of them are checked. Heres the
expression to do so:
LECTURE 5
Library Functions
Library Functions are the in-built functions those are available with VB type
specification that we can use in different forms by writing the proper syntax
they are of different types for e.g.
InputBox: The input box, function display a model dialog box that asks the
uses to enter some data. The dialog box contains a message with two buttons
Ok and Cancel.
E.g. I = Input Box ( Enter a Date, Date Demo)
Msgbox: The Msgbox function is used to display a dialog box, it contains
message with Ok button only (by default). You can also set required Icons
(vbCritical, vbInformation etc) and Buttons (vbYesNo, vbOkCancel etc).
Value Description
VbCritical
16
VbQuestion
32
VbExclamation
VbInformation
48
64
VbSystemModal
4096
End Sub
Add a return button, called cmdBack as you did in the ColourChanger,
using the code
Private Sub cmdBack_Click()
Form1.Show
End Sub
Remarks are added in code to explain the purpose of a section of code or to add
information for code maintenance. If Rem or is placed in front of the remark,
that line
of code is ignored completely.
Run your program using <F5>. Dont forget to save your work.
LECTURE 6
Here are some handy literals (values that dont change). You dont have to learn
them
as the help prompt supplies a drop down list as you start to type.
Value Description
0
Displays the OK button
1
Displays the OK button and Cancel
buttons
If-----Then----End If
If-----Then---Else---End If
Select Case
You might have noticed the indentation style in the previous code
samples; within each block, all statements are indented with respect to
the statements that mark the beginning and the end of the block. This is
not required by Visual Basic, but in my opinion it makes the code more
readable.
And heres an example showing how to use the various parts of this
popular statement:
Dim intInput
intInput = -1
While intInput < 0
intInput = InputBox("Enter a positive number")
Wend
If intInput = 1 Then
MsgBox ("Thank you.")
ElseIf intInput = 2 Then
MsgBox ("That's fine.")
ElseIf intInput >= 3 Then
MsgBox ("Too big.")
End If
LECTURE 7
Select Case Statement
Select Case Structure is an alternative of If----Then----Else End If, for
selectively executing a single block of statements from among multiple blocks of
36/
36/119
Example
Dim intInput
intInput = -1
While intInput < 0
intInput = InputBox("Enter a positive number")
Wend
Const intMax = 100
Select Case intInput
Case 1:
MsgBox ("Thank you.")
Case 2:
MsgBox ("That's fine.")
Case 3:
MsgBox ("Your input is getting pretty big now...")
Case 4 To 10:
MsgBox ("You are approaching the maximum!")
Case Is > intMax:
MsgBox ("Too big, sorry.")
Case Else:
37/
37/119
LECTURE 8
CheckBox Controls
CheckBox controls are useful when you want to offer your users a yes or no,
true or false choice. Anytime you click on this control, it toggles between the yes
state and the no state. 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. For example, if the user clears a check box, you might need to
disable one or more controls on the form and reenable them when the user
clicks on the check box again. This is how you usually do it (here I grouped all
the relevant controls in one frame named Frame1):
Private Sub Check1_Click()
Frame1.Enabled = (Check1.Value = vbChecked)
End Sub
Note that Value is the default property for CheckBox controls, so you can omit it
in code. I suggest that you not do that, however, because it would reduce the
readability of your code.
OptionButton Controls
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.
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 0None.
Controls that are contained in the Frame control are said to be child controls.
Moving a control at design time over a Frame controlor over any other
container, for that matterdoesn'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
LECTURE 9
ListBox Controls
Once you have dropped a ListBox control on a form's surface, you might need to
assign a few properties. For example, you set the Sorted attribute to True to
create ListBox controls that automatically sort their items in alphabetical order.
By acting on the Columns property, you create a different type of list box, with
several columns and a horizontal scroll bar. instead of the default list box with a
single column and a vertical scroll bar along its right border. You can make
assignments for both these properties only at design time, and you can't change
the style of the ListBox control while the program is running.
Both ListBox and ComboBox controls expose the AddItem method, which lets
you add items when the program is executing. You usually use this method in
the Form_Load event procedure:
Private Sub Form_Load()
List1.AddItem "First"
List1.AddItem "Second"
List1.AddItem "Third"
End Sub
Now we can refer to the items in the list box by index using the List property as
List(0), List(1), and so on. When the user clicks the list, causing a Click
event, we can display the item number the user clicked with the ListIndex
property, which holds the index of the currently selected item:
Private Sub List1_Click()
MsgBox "You clicked item " & Str(List1.ListIndex)
End Sub
You can also change an items index with its Index property like this:
List(index).Index = 3
40/
40/119
The ListBox control is even more flexible than I've shown so far because it lets
users select multiple items at the same time. To enable this feature, you assign
the MultiSelect property the values 1-Simple or 2-Extended. In the former case,
you can select and deselect individual items only by using the Spacebar or the
mouse. In extended selection, you can also use the Shift key to select ranges of
items. Most popular Windows programs use extended selection exclusively, so
you shouldn't use the value 1-Simple unless you have a good reason to do so.
The MultiSelect property can't be changed when the program is running, so this
is a design-time decision.
If your list box is a multiselect box, you can determine which items the user has
selected by using the Selected property this way:
For intLoopIndex = 0 To List1.ListCount - 1
If List1.Selected(intLoopIndex) Then
...
End If
Next intLoopIndex
Properties of ListBox
List: Returns/Sets the items contained in a control & list portion, used to enter
the item at a design time.
List Count: Returns the total no. Of items present in the combo box.
List index: Returns the index of the currently selected item in the control.
New index: Returns the index of the item most recently added to control.
Selected: Returns the status of an item whether it is selected or not.
Multiselect: It allows the user to select more than one value from the list.
Columns: Sets a value that determines whether a list box. Scrolls vertically in a
single column (value of 0) or horizontally in shaping columns (values great, than
0).
Events of ListBox
Click: Generalized the user presses and then releases a mouse button on
control.
DblClick: It occurs when the user presses and releases a mouse button and
then presses and releases it again over an object,
Methods of ListBox
AddItem: Used to add an item to Combo Box.
Clear: Clear the contents of the Combo Box.
RemoveItem: Removes an item from a Combo Box by using its index no.
41/
41/119
Combo Box
ComboBox controls are very similar to ListBox controls, so much of what I have
explained so far applies to them as well. More precisely, you can create
ComboBox controls that automatically sort their items using the Sorted
property, you can add items at design time using the List item in the Properties
window, and you can set a ComboBox control's IntegralHeight property as your
user interface dictates. Most run-time methods are common to both kinds of
controls too, including AddItem, RemoveItem, and Clear, as are the ListCount,
ListIndex, List, ItemData, TopIndex, and NewIndex properties and the Click,
DblClick, and Scroll events. ComboBox controls don't support multiple columns
and multiple selections, so you don't have to deal with the Column, MultiSelect,
Select, and SelCount properties and the ItemCheck event.
The ComboBox control is a sort of mixture between a ListBox and a TextBox
control in that it also includes several properties and events that are more
typical of the latter, such as the SelStart, SelLength, SelText, and Locked
properties and the KeyDown, KeyPress, and KeyUp events. I've already
explained many things that you can do with these properties and won't repeat
myself here. Suffice it to say that you can apply to ComboBox controls most of
the techniques that are valid for TextBox controls, including automatic
formatting and deformatting of data in GotFocus and LostFocus event
procedures and validation in Validate event procedures.
The most characteristic ComboBox control property is Style, which lets you pick
one among the three styles available, as you can see in Figure 3-11. When you
set Style = 0-DropDown Combo, what you get is the classic combo; you can
enter a value in the edit area or select one from the drop-down list. The setting
Style = 1-Simple Combo is similar, but the list area is always visible so that in
this case you really have a compounded TextBox plus ListBox control. By
default, Visual Basic creates a control that's only tall enough to show the edit
area, and you must resize it to make the list portion visible. Finally, Style = 2Dropdown List suppresses the edit area and gives you only a drop-down list to
choose from
When you have a ComboBox control with Style = 0-Dropdown Combo or 2Dropdown List, you can learn when the user is opening the list portion by
trapping the DropDown event. For example, you can fill the list area just one
instant before the user sees it (a sort of just-in-time data loading):
Heres an example; in this case, we add four items to a combo boxs list:
Private Sub Form_Load()
Combo1.AddItem ("Item 0")
Combo1.AddItem ("Item 1")
Combo1.AddItem ("Item 2")
Combo1.AddItem ("Item 3")
42/
42/119
Properties of ComBox:
Style: Returns or sets a value that specifies the behavior and/or appearance of
the control.
List: Returns/Sets the items contained in a control & list portion, used to enter
the item at a design time.
List Count: Returns the total no. Of items present in the combo box.
List index: Returns the index of the currently selected item in the control.
New index: Returns the index of the item most recently added to control.
Text: Returns/Sets the text contained in the control.
Events of ComboBox
Click: Generalized the user presses and then releases a mouse button on
control.
DblClick: It occurs when the user presses and releases a mouse button and
then presses and releases it again over an object,
Methods of ComboBox
AddItem: Used to add an item to Combo Box.
Clear: Clear the contents of the Combo Box.
RemoveItem: Removes an item from a Combo Box by using its index no.
LECTURE 10
ScrollBars
Timer controls let you write interesting programs with just a few lines of code.
The typical (and abused) example is a digital clock. Just to make things a bit
more compelling, I added flashing colons:
Private Sub Timer1_Timer()
Dim strTime As String
strTime = Time$
If Mid$(lblClock.Caption, 3, 1) = ":" Then
Mid$(strTime, 3, 1)= " "
Mid$(strTime, 6, 1) = " "
End If
lblClock.Caption = strTime
End Sub
In a sense, the Shape control is an extension of the Line control. It can display
six basic shapes: Rectangle, Square, Oval, Circle, Rounded Rectangle, and
Rounded Square. It supports all the Line control's properties and a few more:
BorderStyle (0-Transparent, 1-Solid), FillColor, and FillStyle (the same as a
form's properties with the same names). The same performance considerations
I pointed out for the Line control apply to the Shape control.
45/
45/119
LECTURE 11
Iteration Control Structure (Loops)
Loops are used to perform repetitive tasks. We places our code in the loop and if
repeats it till some condition.
Loop Structures
Youve seen that Basics decision structures determine whether a block of
statements is executed. In contrast, Basics loop structures control how many
times a block of statements is executed. You can accomplish looping in one of
two ways: by executing a block of statements a fixed number of times or by
executing the block repeatedly until a specified condition is met.
For...Next
In its most common use, the For...Next loop executes a block of statements a
fixed number of times:
For Counter = Start To Stop
...
statement block
...
Next Counter
Counter is a numeric variable that can be any type, although you would
generally use type Integer unless you have a specific reason to use another
type. Start and Stop are the values that specify the start and stop of the loop;
they can be any numeric expression. A For...Next loop begins by setting Counter
equal to Start. It then follows these steps:
1. Counter is compared with Stop. If Counter is greater than Stop, execution
passes to the first statement after the ForNext loop.
2. The statements in the loop are executed.
3. Counter is incremented by 1.
4. Return to Step 1.
Note that if Stop is equal to Start, the loop executes only once; if Stop is less
than Start, it does not execute at all.
Heres an example of a For...Next loop that will execute the number of times
specified by the variable X.
For Count = 1 to X
...
Next X
You are not limited to starting the loop at 1, of course. You can also use the
Step keyword to specify that the Counter variable be incremented by a value
Do...Loop
The Do...Loop structure is the most flexible of Basics loops. It allows the loop to
execute until a specified condition is either True or False, and it allows the
condition to be evaluated either at the start or the end of the loop. In its
simplest form, a Do...Loop executes as long as a condition is True:
Do While Condition
...
statement block
...
Loop
Condition is any logical expression. When execution first reaches the Do
statement, Condition is evaluated. If it is False, execution passes to the
statement following the Loop statement. If it is True, the block of statements is
executed, execution returns to the Do statement, and Condition is evaluated
again. You can also replace the While with the Until keyword to continue
execution for as long as Condition is False, as shown here:
47/
47/119
Do Until Condition
...
statement block
...
Loop
Both of the previous examples perform the comparison at the start of the loop,
which means it is possible for the statement block not to be executedeven
once. For example, if Condition is False to begin with, a Do While
Condition...Loop will not execute even once. If you want to be sure the loop
executes at least once, you can place the Condition at the end of the loop. As
before, you can use either the While or the Until keyword:
Do
...
statement block
...
Loop While Condition
Do
...
statement block
...
Loop Until Condition
To terminate the loop early, use Exit Do. Heres a loop that will execute until Y is
greater than zero or X is less than zero:
Do
...
If X < 0 Then Exit Do
...
Loop Until Y > 0
You may be thinking that we could have obtained the same result by writing the
loop like this:
Do
...
Loop Until Y > 0 Or X < 0
You are correct, but a subtle difference exists between these two loops. In the
first example, the statements between the If X < 0 statement and the Loop
statement are not executed during the last loop iteration, when X becomes less
than zero. In the second example, all of the statements in the loop are executed
during the last execution.
While...Wend
The While...Wend loop executes a block of statements as long as a specified
Condition is True, but it is not nearly as flexible as Do...Loop. In fact, anything
WithEnd With
The WithEnd With statement provides a convenient shorthand when you want
to access more than one property or method of an object. The syntax is:
With object
.Property1 = ...
.Property2 = ...
.Method1
End With
The preceding code has the same effect as the following:
object.Property1 = ...
object.Property2 = ...
object.Method1
When used simply as a shorthand, the WithEnd With statement is at best a
minor convenience. It is more useful when used in procedures that take an
object as a parameter. Here, for example, is a procedure that will change
several font-related properties of any object that is passed to it:
Public Sub ChangeFont(ob As Object)
With ob
.Font.Bold = True
.Font.Italic = True
.ForeColor = RGB(255, 0, 0)
End With
End Sub
LECTURE 12
Explain Some Built-In Functions
1. Numeric Functions: Abs(), Round(), Sqrt(), Rnd, Int(), Fix() etc.
2. String Functions: Chr(), Len(), Str(), Lcase(), Ucase(), strReverse(),
Ltrim(), Rtrim(), Trim(), Left(), Right(), Mid() etc.
3. Date/Time Functions: Month(), Day(), Year() etc.
4. Also explain some other important functions like Format(), RGB(),
QBColor() etc.
LECTURE 13
DriveListBox, DirListBox, and FileListBox Controls
50/
50/119
51/
51/119
Filename = File1.Path
If Right$(Filename, 1) <> "\" Then Filename = Filename & "\"
Filename = Filename & File1.Filename
The DirListBox and FileListBox controls support most of the properties typical of
the control they derive fromthe ListBox controlincluding the ListCount and
the ListIndex properties and the Scroll event. The FileListBox control supports
multiple selection; hence you can set its MultiSelect property in the Properties
window and query the SelCount and Selected properties at run time.
52/
52/119
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 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")
and you can clear the current image using either one of the following
statements:
' These are equivalent.
Picture1.Picture = LoadPicture("")
Set Picture1.Picture = Nothing
Figure 3-16. A minimal but completely functional Image Preview utility that
also supports bitmap tiling.
53/
53/119
LECTURE 14
Arrays
Arrays are a form of variable, but you use them to hold more than one value at
a time. Or you can say that array is a group of variables of some data type all
the elements in an array are differentiated by using their index no.
Arrays have Upper and Lower bounds and the elements have to be within these
bounds. We can disclose an array of any of the basic data types.
Following are the two types of arrays in VB.
Dynamic Arrays
The arrays I have discussed so far are known as static arrays. Their size
number of dimensions and number of elementsis set when the array is
declared and cannot be changed. Another type of array, called dynamic, does
not have these limitations. When you first declare a dynamic array, you specify
its data type, but thats all. For example, the following statement declares a
dynamic array of type Integer:
Dim MyArray() As Integer
Then, when you know the required size of the array, use ReDim to specify it.
Here are some examples:
ReDim MyArray(100)
ReDim MyArray(10,10,20)
ReDim MyArray (1 to 100)
Once you have applied ReDim, you can use the array like any static array. Even
more flexibility is provided by the fact that you can ReDim a dynamic array as
many times as needed, changing the number of dimensions and/or elements to
suit the programs needs. ReDim is permitted only in procedure-level code.
Dynamic arrays follow the same scope rules as static arrays. In other words, if
you declare the array at the module level with Dim, its scope is limited to that
module. To make the dynamic array visible outside the module, use the Public
keyword:
Public MyArray() As Integer
Of course, if you declare a dynamic array at the procedure level its scope is local
to that procedure.
When you use ReDim to change the size of a dynamic array, the default is for
all data in the array to be lost. This means that all elements in the newly sized
array will be initialized to zero (numeric arrays), an empty string (string arrays),
the Empty value (Variant arrays), or Nothing (object arrays). If you want to
change the arrays size while preserving its data, you can do so (with some
limitations) by using the Preserve keyword. Clearly this is applicable only the
second and subsequent times the arrays size is changed with ReDim, otherwise
there will be no data in it to save. Heres how to use Preserve:
ReDim Preserve MyArray(100)
There are some limitations on using Preserve:
If you increase the number of elements in the array, data in the existing
elements will be preserved, and the new elements will be initialized by the usual
rules.
Multidimensional Arrays
Sometimes you need to keep track of related information in an array. For
example, to keep track of each pixel on your computer screen, you need to refer
to its X and Y coordinates. This can be done using a multidimensional array to
store the values.
You can declare arrays of multiple dimensions. For example, the following
statement declares a two-dimensional 10-by-10 array within a procedure:
Dim MatrixA(9, 9) As Double
Either or both dimensions can be declared with explicit lower bounds:
Dim MatrixA(1 To 10, 1 To 10) As Double
You can extend this to more than two dimensions. For example:
Dim MultiD(3, 1 To 10, 1 To 15)
This declaration creates an array that has three dimensions with sizes 4 by 10
by 15. The total number of elements is the product of these three dimensions,
or 600.
Array example: Merging and Finding arrays values & adding arrays etc.
LECTURE 15
Control Arrays
So far, we've dealt with individual controls, each one with a distinctive name
and a distinct set of properties and events. In addition to these, Visual Basic
embodies the concept of control arrays, in which multiple controls share the
same set of event procedures even though each individual element in the array
can have different values for its properties. A control array can be created only
at design time, and at the very minimum at least one control must belong to it.
You create a control array following one of these three methods:
You create a control and then assign a numeric, non-negative value to its Index
property; you have thus created a control array with just one element.
You create two controls of the same class and assign them an identical Name
property. Visual Basic shows a dialog box warning you that there's already a
control with that name and asks whether you want to create a control array.
Click on the Yes button.
You select a control on the form, press Ctrl+C to copy it to the clipboard, and
then press Ctrl+V to paste a new instance of the control, which has the same
57/
57/119
LECTURE 16
Types of Interfaces
SDI: Single Document Interface.
MDI: Multiple Document Interface.
SDI: An application that supports only one document at a time called SDI
application. In SDI we cannot use multiple documents simultaneous, Paintbrush,
Notepad and WordPad are the examples of SDI applications.
MDI: Application such a MS-Excel and MS-Word have multiple documents
interface. To add a MDI forms click on project menu, and then the option ADD
MDI Form. It allows you to create an application that maintains multiple forms
within single contain form. They allow you to display multiple documents at the
same time, with each document displayed in its own window. Documents or
Child windows are contained in a parent window, which provides a workspace
for all the child windows in the application. For example, Microsoft Excel allows
you to create and display multiple-document windows of different types. Each
individual window is confined to the area of the Excel parent window. When you
59/
59/119
60/
60/119
child
MDI
child
child
Well create an MDI application which uses a simple, text box-based, editor as
the child application. There are a lot of steps, even for a simple example.
Start a new application. Create a parent form by selecting MDI Form from
the Insert menu. At this point, the project will contain an MDI parent form
(MDIForm1) and a standard form (Form1) which we will use as a child
form. Make MDIForm1 the startup form. We work with the parent form first:
1. Set the following properties:
Caption
Name
WindowState
MDI Example
frmParent
2-Maximized
Caption
&File
&New
&Arrange
&Cascade
&Horizontal Tile
&Vertical Tile
&Arrange Icons
Name
Indented
mnuFile
No
mnuFileNew
Yes
mnuArrange
No
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index
=
=
=
=
0
1
2
3
61/
61/119
This
62/
62/119
Now, well work with Form1 which will hold the child application:
5. Draw a text box on the form.
form and the text box:
Form1:
Caption
MDIChild
Name
Visible
Child Form
True
frmChild
False
Text1:
Left
MultiLine
ScrollBars
Text
Top
0
True
2-Vertical
[Blank]
0
then
the Menu
not
yet
blank.
menu
menu
Windows
64/
64/119
Figure 11.3 The Menu Editor after partially completing the File menu.
After entering the Exit command and clicking on Next, you are ready to start
with the Edit menu. At this point, any entry you make will be subsidiary to the
File menu. Because we want Edit to be a top-level menu, you need to click on
the left arrow button to move up one level on the outline. Assign the caption
&Edit and the name mnuEdit to this menu item, then click on Next. Click on the
right arrow to move down one level on the outline, and add the commands
shown in Table 11.1 to the Edit menu.
Thats itthe menu is finished. Your Menu Editor will look like the one shown in
Figure 11.4. Click on OK to close the Menu Editor and return to the form. You
will see the menus on the form during design and when the program runs. You
can open the menus and select commandsalthough nothing happens, because
we havent written event code for the menu commands yet.
Table 11.1 Edit menu commands.
Caption
&Copy
Cu&t
&Paste
-
Name
mnuEditCopy
mnuEditCut
mnuEditPaste
mnuEdit Separator
Shortcut Key
Ctrl+C
Ctrl+X
Ctrl+V
65/
65/119
Ctrl+F
Pop-up Menu
Visual Basic also supports pop-up menus, those context-sensitive menus that
most commercial applications show when you right-click on an user interface
object. In Visual Basic, you can display a pop-up menu by calling the form's
PopupMenu method, typically from within the MouseDown event procedure of
the object:
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
If Button And vbRightButton Then
' User right-clicked the list box.
PopupMenu mnuListPopup
End If
End Sub
The argument you pass to the PopupMenu method is the name of a menu that
you have defined using the Menu Editor. This might be either a submenu that
you can reach using the regular menu structure or a submenu that's intended to
work only as a pop-up menu. In the latter case, you should create it as a toplevel menu in the Menu Editor and then set its Visible attribute to False. If your
program includes many pop-up menus, you might find it convenient to add one
invisible top-level entry and then add all the pop-up menus below it. (In this
case, you don't need to make each individual item invisible.) The complete
syntax of the PopupMenu method is quite complex:
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]
LECTURE 17
ActiveX control (Extrinsic controls)
An ActiveX control is an extension to the VB Toolbox. You are the active controls
just as you would do in any of the standard
built in
control such as the check control.
ActiveX controls have the file name extension
You can use the ActiveX controls provided
.OCX.
with
Toolbars
The toolbar control makes it easy to build toolbars into your project. Toolbars
are an extremely useful enhancement to menus. They provide mouse driver
short to menu option. Normally the toolbars appears on the top, so the align
property deputes to 1 (top).
If you want images to appear in your toolbar, you must first store them in an
image list control. If you intend to set the images at design time, the associated
imagers control must be on the same form as the toolbar after the images are
stored in an image list control. You set the image list properties of the toolbar
control to be the name of the image list control.
Toolbar Control
Almost all Windows applications these days use toolbars. A toolbar provides
quick access to the most frequently used menu commands in an application.
The toolbar control is a mini-application in itself. It provides everything you
need to design and implement a toolbar into your application. This control is
part of a group of controls loaded by selecting the Microsoft Windows
Common Controls from the Components dialog box.
68/
68/119
69/
69/119
ToolTipText Image
New File
1
Open File
2
Save File
3
Print File
4
-None0
Help me!
5
Save and run the application. Note the buttons just click - we didnt write
any code (as mentioned earlier, the code is usually just a call to an existing
menu items click event). Check out how the tool tips work.
Quick Note on Tooltips:
Many of the Visual Basic controls support tooltips to inform the user of what a
particular control. Simply set individual controls ToolTipText property to a
non-blank text string to enable this capability.
Status bar
The statues bar control gives you a window that you can use to display the
status the application. Each status bar can be divided into cat most 16 panels.
At design item you can add the individual panels by using the panels page of the
custom property dialog box. You can add both text and a picture to the panel by
working with this dialog box.
The StatusBar control exposes a Panels collection, which in turn contains Panel
objects. A Panel object is an area of the status bar that can hold a piece of
72/
72/119
LECTURE 18
Progress Bar
The progress bar control enables the users to get a feedback about a lengthy
operation by pictorially displaying a moving colored bar.
The ProgressBar control is used to inform the user about the progress state of a
lengthy operation. This control is the simplest one among those contained in the
MsComCtl.OCX file because it doesn't have any dependent objects and it doesn't
expose any custom events.
Setting Design-Time Properties
You have to set up a few properties at design time after you drop a ProgressBar
control on a form; in most cases, you can accept the default values. The most
important properties are Min and Max, which determine the minimum and
maximum values that can be displayed by the progress bar.
The ProgressBar control that comes with Visual Basic 6 includes two new
properties, Orientation and Scrolling. The former lets you create vertical
progress bars; the latter lets you alternate between a standard segmented bar
and a smoother bar, as you can see in Figure 10-24. You can change these
values even at run time.
Slider Control
The slider control is similar to a scroll bar yet allows the ability to select
a range of values, as well as a single value. This control is part of a group
of controls loaded by selecting the Microsoft Windows Common
Controls from the Components dialog box.
Possible uses for this control include:
To set the value of a point on a graph.
To select a range of numbers to be passed into an array.
To resize a form, field, or other graphics object.
Slider Control Properties:
Figure 10-22. The Panels tab of the Property Pages dialog box of a StatusBar
control.
Value
Current slider value.
Min, Max
Establish upper and lower slider limits.
TickFrequency
Determines how many ticks appear on
slider.
73/
73/119
TickStyle
Determines how and where ticks appear.
SmallChange Amount slider value changes when user presses
left or right arrow keys.
LargeChange Amount slider value changes when user clicks
the slider or presses PgUp or PgDn arrow keys.
SelectRange Enable selecting a range of values.
SelStart
Starting selected value.
SelLength
Length of select range of values.
Run the application. Establish a starting value for the selected range by
moving the slider to a desired point. Then, click the slider thumb while
holding down the Shift key and move it to the desired upper value.
74/
74/119
If Shift = 1 Then
Slider1.SelLength = Slider1.Value - Slider1.SelStart
Label2.Caption = Slider1.Value
Else
Slider1.SelLength = 0
End If
End Sub
As
Integer,
Shift
As
Dialog displayed
Open
Save As
Color
Font
Print
Invokes Windows Help
75/
75/119
76/
76/119
LECTURE 19
Procedures & Functions
Event procedures: Much of the programmers code in visual basic that tells you
program how to respond to such as mouse clicks occurs in what visual basic
calls event procedure. An event procedure is nothing more than the code
needed to tell visual basic how to respond to event. E.g.. Click event of a
command button.
Private Sub command_Click ()
Statements
End Sub
Sub Procedures: Sub procedures or just subs, are procedures that can
accept arguments, execute code, and change the values of passed arguments.
Arguments are variables that are passed to a sub so that the sub can process
the data stored in the argument.
Public Sub procedureName ()
Statements
End Sub
Function Procedures: Functions are much like subs except they return a
value to the calling procedure. They are especially useful for taking one or more
pieces of data, called arguments, and performing since tasks with them. Then
the function returns a value that indicates the result of the tasks completed
within the function e.g.
Public Function Sum (A as integer) As Integer
Statements
End Function
Passing Arguments
By Reference: The ByRef prefix indicates that the parameters are passed by
reference, which is the defaults method in VB. When a variable is passed by
reference, the memory address of the variable is passed to the function. This
allows the functions or sub to modify the actual value of the variable. Syntax:
Function FunctionName (ByRef variable as dataType) as dataType.
Statements
End Function
TreeView Control
The TreeView control lets you display and manipulate items in a hierarchical
view. An example that most of us see every day is Windows Explorer, which
uses a TreeView control to display folders and file names. You can select single
or multiple items, open and close branches on the tree, and control the way
items are displayed. Each item in a TreeView can have an icon associated with
it, such as the file folder and page icons used in Windows Explorer. Youre not
limited to disk-related items, thougha TreeView control can be used for any
information that is arranged hierarchically.
To be honest, the TreeView control is not all that easy to understand and use. It
is a complicated control, and it doesnt provide the almost-instant gratification
that we Visual Basic programmers have perhaps become too accustomed to.
Youll have to exercise your noggin a bit before you can get a TreeView control
doing just what you want it to.
The main reason for the TreeView controls complexity is its structure. It is not,
as are most Visual Basic controls, just a single object with a set of properties
and methods. Oh no, that would make life too easy. Let me explain:
Each item on a TreeVieweach twig on the treeis a Node object. Each of
these Node objects has its own set of properties and methods.
All of the Node objects belonging to a particular TreeView are organized in
the Nodes collection, which is itself an object with methods and
properties. One of the Nodes collections methods is Item, which is used
to access the individual Node objects in the collection.
The TreeView control itself is an object with methods and properties. One
of its properties is Nodes, which refers to its Nodes collection.
The TreeView object is (optionally) associated with an ImageList object
that holds the images to be displayed at the tree nodes.
You can probably see where the confusion comes from. When you want to do
something with a TreeView object, its not always clear whether you use the
methods and properties of the TreeView object itself, or whether you must
manipulate its associated Nodes collection or, perhaps, work directly with a
Node object.
While the TreeView control by itself can be useful, it really comes into its own
when you associate each node in the tree with something else. When TreeView
is used for a folder/file display, the association is automatic. What about other
associations? Ill be showing you how to associate a Text Box with each node in
a tree, and you can use the same or similar techniques to associate other
objects with TreeView nodes. I cant show all the details of using the TreeView
control, but I can get you started so you can explore further on your own. Ill
include a sample application that illustrates the techniques I cover.
LECTURE 20
The Main Benefits of OOP
Encapsulation
Encapsulation is probably the feature that programmers appreciate most in
object-oriented programming. In a nutshell, an object is the sole owner of its
own data. All data is stored inside a memory area that can't be directly accessed
Polymorphism
Informally, Polymorphism is the ability of different classes to expose similar (or
identical) interfaces to the outside. The most evident kind of polymorphism in
Visual Basic is forms and controls. TextBox and PictureBox controls are
completely different objects, but they have some properties and methods in
common, such as Left, BackColor, and Move. This similarity simplifies your job
as a programmer because you don't have to remember hundreds of different
names and syntax formats. More important, it lets you manage a group of
controls using a single variable (typed as Control, Variant, or Object) and create
generic procedures that act on all the controls on a form and therefore
noticeably reduce the amount of code you have to write.
Inheritance
Inheritance is the ability, offered by many OOP languages, to derive a new class
(the derived or inherited class) from another class (the base class). The derived
class automatically inherits the properties and methods of the base class. For
example, you could define a generic Shape class with properties such as Color
and Position and then use it as a base for more specific classes (for example,
Rectangle, Circle, and so on) that inherit all those generic properties. You could
then add specific members, such as Width and Height for the Rectangle class
and Radius for the Circle class. It's interesting to note that, while polymorphism
tends to reduce the amount of code necessary to use the class, inheritance
reduces the code inside the class itself and therefore simplifies the job of the
class creator. Unfortunately, Visual Basic doesn't support inheritance, at least
not in its more mature form of implementation inheritance.
Form Modules
Form modules (.FRM file name extension) are the foundation of most Visual
Basic applications. They can contain procedures that handle events, general
procedures, and form-level declarations of variables, constants, types, and
external procedures. If you were to look at a form module in a text editor, you
would also see descriptions of the form and its controls, including their property
settings. The code that you write in a form module is specific to the particular
application to which the form belongs; it might also reference other forms or
objects within that application.
Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They
can contain global (available to the whole application) or module-level
declarations of variables, constants, types, external procedures, and global
procedures. The code that you write in a standard module isn't necessarily tied
to a particular application; if you're careful not to reference forms or controls by
name, a standard module can be reused in many different applications.
Class Modules
Class modules (.CLS file name extension) are the foundation of object-oriented
programming in Visual Basic. You can write code in class modules to create new
objects. These new objects can include your own customized properties and
methods.
Code Module
Code in Visual Basic is stored in modules. There are three kinds of modules:
form, standard, and class.
Simple applications can consist of just a single form, and all of the code in the
application resides in that form module. As your applications get larger and
more sophisticated, you add additional forms. Eventually you might find that
there is common code you want to execute in several forms. You don't want to
duplicate the code in both forms, so you create a separate module containing a
procedure that implements the common code. This separate module should be a
standard module. Over time, you can build up a library of modules containing
shared procedures.
LECTURE 21
Error Handling
Error: Any bug is a program (code) is called an error. It effects the execution of
the code adversely programming errors can of the following three types.
Syntax Error: Occurs when we enter an incorrect line of code such as a
mistake in typing a keyword. A punctuation is mirror as an incorrectly speeded
variable.
Description
On Error Resume Next Specifies that when a run-time error occurs, control
goes to the statement immediately following the
statement where the error occurred where execution
continues. Use this form rather than On Error GoTo
when accessing objects.
On Error GoTo 0
If you don't use an On Error statement, any run-time error that occurs is fatal;
that is, an error message is displayed and execution stops.
Error-handling routines rely on the value in the Number property of the Err
object to determine the cause of the error. The error-handling routine should
Raising Errors
When working on your projects error-handling code, mimicking the occurrence
of certain runtime errors is often useful, so you can see exactly how your errorhandling routines work. You can mimic errors in code using the ERR objects
Raise method. The syntax is as follows:
Err.Raise number, source, description, helpfile, helpcontext
The only required argument is number, which is a Long integer that identifies
the error. To mimic a specific Visual Basic error, use the number associated with
the error, as indicated in the Help information. The other arguments are
optional:
sourceString expression naming the object or application that generated
the error. When setting this property for an object, use the form project.class. If
source is not specified, the programmatic ID of the current Visual Basic project
is used.
descriptionString expression describing the error. If unspecified, the value
in number is examined. If it can be mapped to a Visual Basic runtime error
code, the string that would be returned by the Error function is used as
description. If no Visual Basic error corresponds to number, the Applicationdefined or object-defined error message is used.
helpfileThe fully qualified path to the Microsoft Windows Help file in which
help on this error can be found. If unspecified, Visual Basic uses the fully
qualified drive, path, and file name of the Visual Basic Help file.
helpcontextThe context ID identifying a topic within helpfile that provides
help for the error. If omitted, the Visual Basic Help file context ID for the error
corresponding to the Number property is used, if it exists.
LECTURE 22-23
Component Object Model (COM)
COM is the basis for all OCX controls. COM is a specification. It doesnt tell the
user hw to implement a control; rather it concentrates on the way in which two
processes communicate with each other and defines some standard interfaces
for them to communicate. COM allows software components to communicate
with each other. It is a binary standard that allow any two components to
communicate regardless of the language the components are written in. The
only way to access and interact with a COM object is through interfaces. An
open architecture for cross-platform development of client/server applications
based on object-oriented technology. Clients have access to an object through
interfaces implemented on the object. COM is language neutral, so any language
that produces ActiveX components can also produce COM applications.
Distributed Component Object Model (DCOM)
It allows information exchange over the Internet, the local intranet or any other
network. While COM is the basis for OCX controls, DCOM is the basis for ActiveX
controls-as ActiveX itself is nothing but Internet enabled OCX. OCX supports
links to other machines, but the code for that link would be executed locally.
DCOM allows the user to create OLE links that rely on code stored on the
machines. In many cases the code will also execute remotely.
Constituents of ActiveX Control
An ActiveX control can be developed in a way similar to that of developing
applications. The ActiveX Control Interface Wizard takes care of intricate parts of
the code and generates an outline to which the code can be added to implement
unique functions.
Types of ActiveX Controls
Visual Basic offers the user three different types of controls. The techniques for
authorizing all ActiveX controls are the same. The different types of ActiveX
controls offered by Visual Basic are as follows.
User Drawn Controls: These controls are developed from scratch. The
user is responsible for designing the controls interface and is in control of
its appearance and interface. These implementation of thee controls is
LECTURE 25-26
LECTURE 24
Introduction to ActiveX DLLs and ActiveX EXE
Visual Basic can be used to compile class-based projects such as ActiveX
components. These components can either take the form of DLLs and EXEs. The
components offer us the ability to provide the functionality of objects without
having to redistribute or duplicate the source code of our classes. When an
object variable is created to access the properties and methods of a class, we
are actually invoking an executable file (DLL or EXE) that runs in the
background and waits to be contacted. This is activated every time a property
value is set or read or a method is called.
Database
A database is a collection of information, or data, arranged in a particular
manner. The basic unit of information in a database is called a record. Each
record in a database contains two or more fields that hold specific types of
information. Perhaps the most common example of a database is an address
list. Each entry in the database constitutes one record: an individuals name and
address information. Each record in the database contains fields that hold
separate items of information: first name, last name, address, city, and so on.
These fields are the same for every record in the database, and they are
assigned names identifying the data they contain.
ActiveX DLLs
ActiveX DLL (Dynamic Link Library) always run a In-Process servers as they are
given space in the calling programs address space. It gets linked with your code
at run time and provides functionalities to your code. This increases the
performance considerably. Since DLLs run in another applications process space
so can never be run alone.
ActiveX EXE
ActiveX EXE always run in their process space (out-of-process server) therefore
always there is an overhead as data needs to be transferred access the
application boundaries. The advantage of EXEs is that they can run as standard
applications and they act as code component for other application.
OLE DB
ADO
ActiveX Data Objects provide Visual Basic programmers with an application-level
interface to OLE DB. You rarely, if ever, need to worry about OLE DBits just
there doing its jobso you can think of ADO as an interface directly to the data
source. ADO is new in this release of Visual Basic and is considered by Microsoft
to be its premier data access technology. If you have used earlier versions of
Visual Basic for database programming, you may be familiar with the older
technologies: Remote Data Objects (RDO) and Data Access Objects (DAO).
These technologies are still supported by Visual Basic. In fact, the Data control,
used in the sample application developed in Chapter 19, makes use of these
ODBC
Open Database Connectivity (ODBC) provides an Applications Programming
Interface (API) that contains procedures for performing various datamanipulation tasks. A program calls these API procedures, as needed, and the
ODBC Driver Manager passes the calls to the appropriate driver. Appropriate
means the driver that is designed for the particular data source that is in use.
This is where the open part of the ODBC name comes from. Any data source
publisher can write an ODBC driver for its own data format.
ODBC is generally considered obsolete. The only reason to use ODBC in a new
database project is if you need to access a data source that is in an obscure
format, unsupported by ADO, for which an ODBC driver exists. Even in this
situation, you probably are better off opting to use DAO, because it supports
ODBC databases.
DAO
Data Access Objects (DAO) is similar to ODBC in that it provides an API that
your program can call to perform data-manipulation tasks. DAO differs from
ODBC in that it uses the Microsoft Jet Database Engine rather than a driver
provided by the data source publisher. DAO is optimized to work with data
source files in the MDB format (the same format used by the Microsoft Access
database program). However, DAO also supports ODBC databases, as well as
data sources in a variety of formats, including Paradox, FoxPro, dBase, Excel,
and Lotus 1-2-3.
The Remote Data Objects (RDO) programming model was developed specifically
to deal with the special requirements of accessing the data source via a
network, referred to as remote data access. RDO works by adding a layer on top
of ODBC to handle the special needs of remote access, such as establishing
connections and creating results sets. In some situations, RDO works with DAO
to perform the required tasks. RDO can be implemented totally in code or via
the RemoteData control.
Implementing RDO in a Visual Basic application is very similar to using DAO. In
fact, a Visual Basic application that uses the Data control and DAO can easily be
converted to use the RemoteData control and RDO. The few differences arise
primarily because RDO is designed for use only with strictly relational databases.
RDO relies on the data source to process queries because RDO has no query
processor of its own.
You can delete a record in a database with the Delete method of the
Recordset property of a data or an ADO data control, or of the Resultset
property of a remote data control. Lets see an example. When the user clicks
the Delete button in the dbmethods example were developing in this and the
previous few topics, we can delete a record like this:
Private Sub cmdDelete_Click()
Data1.Recordset.Delete
...
End Sub
To avoid displaying a blank record, we also move to the next record this way:
Private Sub cmdDelete_Click()
Data1.Recordset.Delete
Data1.Recordset.MoveNext
End Sub
After changing the fields in a record, you can update a database with the
UpdateRecord method of the data, ADO data control, or remote data control.
RDO
94/
94/119
Recordset: Record sets are objects that represent collectors of records from
one of more tables. Recordset are equivalent of variables in regular
programming you can access the tables of database only by manipulating the
Recordset objects. A Recordset is a view of some data in the database, selected
from the database according to user specified criteria. In other word, A
Recordset represents the entire set of records from a table in a database or that
result from an executed command. A Recordset is a set of rows in which each
row has columns of data.
There are three types of Recordset namely.
(i)
Dynasets, which are updateable views of data.
(ii) Snapshots which are static (Read-only) views of data
(iii) Table, which are direct views of table.
Data Access Object: DAO was the first object-oriented interface that
You can move to the previous record of a database with the MovePrevious
method of the Recordset property of a data or ADO data control, or of the
Resultset property of a remote data control. Lets see an example. When the
user clicks the Previous button in the dbmethods example were developing in
this and the previous few topics, we can move to the previous record like this:
Private Sub cmdPrevious_Click()
Data1.Recordset.MovePrevious
End Sub
exposed the Microsoft Jet database engine and allowed Visual Basic developers
to directly connect to Access tables - as well as other databases - through
ODBC. DAO is suited best for either single-system applications or for small, local
deployments. DAO enables you to use a programming language to access and
manipulate data in local or remote databases, and to manage databases, their
objects, and their structure. DAO supplies a hierarchical set of objects that use
the Microsoft Jet database engine to access data and database structure in:
95/
95/119
LECTURE 27-28
ActiveX Data Objects (ADO): ADO enables you to write a client application to
access and manipulate data in a data source through a provider. ADO is ideally
suited to consume data exposed by OLE DB providers. OLE DB provides highperformance access to any data source, including relational and non-relational
databases, email and file systems, text and graphics, custom business objects,
and more. ADO connects to a database by means of OLEDB provides OLEDB
provides is a Microsoft lower-level database interface that provides access to
many different kinds of data. It expresses their database of ADO.
Possible Uses
Connect to a local or remote database.
Open a specified database table or define a set of records based on a
Structured Query Language (SQL) query or stored procedure or view of the
tables in that database.
Pass data field values to data-bound controls, where you can display or
change the values.
Add new records or update a database based on any changes you make to
data displayed in the bound controls.
To create a client, or front-end database application, add the ADO Data control
to your forms just as you would any other Visual Basic control. You can have as
many ADO Data controls on your form as you need.
To create a simple front-end database application
1. Draw an ADO Data Control on a form.
If the control is not available in the Toolbox, press CTRL+T to display the
Components dialog box. In the Components dialog, click Microsoft ADO
Data Control 6.0 (OLEDB).
2. On the Toolbox, click the ADO Data Control to select it. Then press F4 to
display the Properties window.
3. In the Properties window, set the RecordSource property to a Table or
SQL statement. For example: SELECT * FROM Titles WHERE AuthorID = 72
4. Draw a TextBox control on the form to display the database information.
5. In the Properties window, set the DataSource property for Text1 to the
name of the ADO Data control (ADODC1). This binds the text box to the
ADO Data control.
6. In the Properties window, click DataField and a list of available fields will
drop down. Click the name of the field you want to display.
Option Explicit
Dim msgRes As VbMsgBoxResult
Private Sub cmdAdd_Click()
Text1.Locked = False
Text2.Locked = False
Text3.Locked = False
97/
97/119
cmdSave.Enabled = True
cmdCancel.Enabled = True
cmdAdd.Enabled = False
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
cmdClose.Enabled = False
Text1.SetFocus
Adodc1.Recordset.AddNew
End Sub
Private Sub cmdCancel_Click()
On Error GoTo errMess
Adodc1.Recordset.CancelUpdate
ButtonSettings
Exit Sub
errMess:
MsgBox Err.Description, vbCritical
ButtonSettings
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub cmdDelete_Click()
msgRes = MsgBox("Are you sure?", vbQuestion + vbYesNo)
If msgRes = vbYes Then
Adodc1.Recordset.Delete
ButtonSettings
End If
End Sub
Private Sub cmdFirst_Click()
Adodc1.Recordset.MoveLast
98/
98/119
99/
99/119
errMess:
MsgBox Err.Description, vbCritical
End Sub
Private Sub Form_Load()
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Program Files\Microsoft Visual
Studio\VB98\Database\Nwind.mdb;Persist Security Info=False"
Adodc1.RecordSource = "Select * from Employees"
Set
Set
Set
Set
Set
Text1.DataSource
Text2.DataSource
Text3.DataSource
Text4.DataSource
Text5.DataSource
Text1.DataField
Text2.DataField
Text3.DataField
Text4.DataField
Text5.DataField
=
=
=
=
=
=
=
=
=
=
Adodc1
Adodc1
Adodc1
Adodc1
Adodc1
"FirstName"
"LastName"
"Address"
"BirthDate"
"HomePhone"
ButtonSettings
End Sub
Public Sub ButtonSettings()
On Error Resume Next
cmdAdd.Enabled = True
cmdClose.Enabled = True
cmdSave.Enabled = False
cmdCancel.Enabled = False
Adodc1.Recordset.MoveLast
Adodc1.Recordset.MoveFirst
If Adodc1.Recordset.RecordCount = 0 Then
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
ElseIf Adodc1.Recordset.RecordCount = 1 Then
cmdFirst.Enabled = False
=
=
=
=
=
100/
100/119
True
True
True
True
True
LECTURE 29-30
Cursor
In database technology, a piece of software that returns rows of data to the
requesting application. A cursor keeps track of the position in the result set, and
multiple operations can be performed row by row against a result set with or
without returning to the original table. In other words, cursors conceptually
return a result set based on tables within the databases. The cursor is so named
because it indicates the current position in the result set, just as the cursor on a
computer screen indicates current position.
Sets or returns the location of the cursor engine.
Settings And Return Values
Sets or returns a Long value that can be set to one of the following constants.
Constant
Description
AdUseNone
AdUseClient
101/
101/119
enabled.
For
backward
compatibility,
the
synonym adUseClientBatch is also supported.
AdUseServer Default. Uses data-provider or driver-supplied
cursors. These cursors are sometimes very
flexible and allow for additional sensitivity to
changes others make to the data source.
However, some features of the Microsoft Client
Cursor
Provider
(such
as
disassociated
recordsets) cannot be simulated with server-side
cursors and these features will be unavailable
with this setting.
102/
102/119
Use the CursorType property to specify the type of cursor that should be used
when opening the Recordset object. The CursorType property is read/write when
the Recordset is closed and read-only when it is open.
Only a setting of adUseStatic is supported if the CursorLocation property is set
to adUseClient. If an unsupported value is set, then no error will result; the
closest supported CursorType will be used instead.
If a provider does not support the requested cursor type, the provider may
return another cursor type. The CursorType property will change to match the
actual cursor type in use when the Recordset object is open. To verify specific
functionality of the returned cursor, use the Supports method. After you close
the Recordset, the CursorType property reverts to its original setting.
Constant
Constant
Description
AdLockReadOnly
AdLockPessimistic
AdLockOptimistic
Description
AdOpenDynamic
103/
103/119
error
Disrupter
Contains the records that made us the
resets of query
Allows control over the connection to
the data source.
field Executes database commands and
cursor determines errors from ADO.
Represents a piece of data in Recordset
works with the command object to set
up a parameters in a query or stored
procedure.
A reference to the project must be added to use these ADO objects, by choosing
projects. References place a check mark to the Microsoft. ActiveX Data objects
2.6 library and click the ok button.
Option Explicit
Dim msgRes As VbMsgBoxResult
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Private Sub cmdAdd_Click()
Text1.Locked = False
Text2.Locked = False
104/
104/119
cmdSave.Enabled = True
cmdCancel.Enabled = True
cmdAdd.Enabled = False
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
cmdClose.Enabled = False
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text1.SetFocus
rs.AddNew
End Sub
Private Sub cmdCancel_Click()
On Error GoTo errMess
rs.CancelUpdate
ButtonSettings
Exit Sub
errMess:
MsgBox Err.Description, vbCritical
ButtonSettings
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub cmdDelete_Click()
msgRes = MsgBox("Are you sure?", vbQuestion + vbYesNo)
If msgRes = vbYes Then
rs.Delete
ButtonSettings
RecordPrint
105/
105/119
106/
106/119
rs.Update
ButtonSettings
RecordPrint
Exit Sub
errMess:
MsgBox Err.Description, vbCritical
End Sub
rs.CursorType = adOpenDynamic
rs.LockType = adLockOptimistic
rs.ActiveConnection = cn
rs.Open "Select * from Employees"
'or: rs.open "Select * from Employees",cn,adOpenDynamic,adLockOptimistic
RecordPrint
ButtonSettings
End Sub
Public Sub ButtonSettings()
On Error Resume Next
cmdAdd.Enabled = True
cmdClose.Enabled = True
cmdSave.Enabled = False
cmdCancel.Enabled = False
=
=
=
=
=
True
True
True
True
True
LECTURE 31
DBGrid Control
107/
107/119
The data-aware DataGrid control appears similar to the Grid control; however,
you can set the DataGrid control's DataSource property to a Data control so
that the control is automatically filled and its column headers set automatically
from a Data control's Recordset object. The DataGrid control is really a fixed
collection of columns, each with an indeterminate number of rows.
Each cell of a DataGrid control can hold text values, but not linked or
embedded objects. You can specify the current cell in code, or the user can
change it at run time using the mouse or the arrow keys. Cells can be edited
interactively, by typing into the cell, or programmatically. Cells can be selected
individually or by row.
If a cell's text is too long to be displayed in the cell, the text wraps to the next
line within the same cell. To display the wrapped text, you must increase the
cell's Column object's Width property and/or the DataGrid control's
RowHeight property. At design time, you can change the column width
interactively by resizing the column or by changing the column's width in the
Column object's property page.
Use the DataGrid control's Columns collection's Count property and the
Recordset object's RecordCount property to determine the number of
columns and rows in the control. A DataGrid control can have as many rows as
the system resources can support and up to 32767 columns.
When you select a cell, the ColIndex property is set, thus selecting one of the
Column objects in the DataGrid object's Columns collection. The Text and
Value properties of the Column object reference the contents of the current
cell. The data in the current row can be accessed using the Bookmark property,
which provides access to the underlying Recordset object's record. Each
column of the DataGrid control has its own font, border, word wrap, and other
attributes that can be set without regard to other columns. At design time, you
LECTURE 32-33
Connection Objects
At design time, you can use the Data Environment designer to create a
DataEnvironment object. The DataEnvironment object can include Connection
and Command objects, hierarchies (relationships between Command objects),
groupings, and aggregates. Before designing your DataEnvironment object, you
should determine what information you want to present, identify the databases
that contain the information, and determine your run-time objective (for
example, creating a Data Report or Hierarchical FlexGrid control).
Before you can access the Data Environment designer, you must reference it in
Visual Basic.
To access data using your Data Environment, you must create a Connection
object. Therefore, every Data Environment should include at least one
Connection object. A Connection object represents a connection to a remote
database that is used as a data source.
Upon adding a Data Environment to your Visual Basic project, the Data
Environment designer automatically includes a new connection, called
Connection1. At design time, the Data Environment opens the connection and
obtains metadata from the connection, including database object names, table
structures, and procedure parameters.
Purpose
Command
Name
Connection
Database
Object
Object Name
112/
112/119
Design-Time Operations
The simplest way to create a report using the DataReport designer is in
conjunction with the DataEnvironment designer. The DataReport designer
supports drag-and-drop operations of DataEnvironment's Command objects,
including hierarchical Command objects. The only limitation is that the report
can account for just one child Recordset at each nesting level. For all the
examples in this chapter, I'll use a hierarchical Command object based on the
Orders and Order Details tables in the NWind.mdb database.
Figure 15-8. The DataReport designer at design time, with the pop-up
menu that appears when you right-click on a control.
Lecture 34
The Package And Deployment Wizard
The Package and Deployment Wizard (or PD Wizard) is on the same level as
sliced bread and indoor plumbing in terms of being a great thing. Assembling all
the files needed to distribute your Visual Basic application and packaging them
for distribution would be a miserable task without this tool. You can run the PD
The next screen (Figure 26.7) lists all of the files the PD Wizard will include in
your setup package. To add files,
click on
the Add button. Files you might
need to
add include a READ.ME file, help
files,
licensing information, and the
like.
You should never need to add an
actual
program component, because the
PD
Wizard will have already included
all
required items. You can also
remove
a file from the distribution
package
by clearing the checkbox next to
its
name in the list. I strongly
suggest
that you never do this, because
the files
included in the list are required for your application to install and run correctly.
The next screen lets you select whether your package will be compressed into a
single cab file (a cab file, short for cabinet, is a type of compressed file used by
Microsoft for program distribution) or into multiple cabs. If you select multiple
cabs, you can also select the maximum size for each file to match the
distribution media. For example, select 1.44MB if your program will be
distributed on standard high-density diskettes.
The next few screens let you select options, such as the name your program will
be assigned when it is installed and the location of the program on the users
Start menu. You can make your selections, using the PD Wizard prompts to help
you if needed. When asked whether to designate shared files, accept the default