Visual Basic Question & Answers
Visual Basic Question & Answers
TWO MARKS
6. Define FORM.
A form is a container in visual basic IDE which is used to place various controls based on
the application requirements. Also it is a blank window in visual basic contains the grid of
dots.
7. What is a variable?
A variable is a name given to a memory location where a data value will be stored. The
value of a variable may be changed at any time during program execution.
8. Give the purpose of a command button
The command button control is used to begin, interrupt, or end a process. When clicked, it
invokes a command that has been written into its Click event procedure. Most Visual
Basic applications have command buttons that allow the user to simply click them to
perform actions.
a) Integer
b) String
c) Date
d) Boolean
e) Variant
i. Integer Data Type
But these Data type categories are divided into more sub data types.
The Toolbox is the selection menu for controls used in our application.
Altering a Form: To change the position of a form at run time,
a) Move the cursor to the form Layout Window.
b) Drag the form to the position where we want to appear at runtime.
The Project Window displays a list of all forms and modules making up our application.
Common Form properties:
i. Caption: This property sets the title of the form.
ii. Name: This property is used in the code to identify the object (control).
iii. Appearance: It is used to determine how the form looks on the screen
iv. BorderStyle: It determines border style of the form.
v. Enabled: It determines whether an object can respond to user generated events
vi. Font: This property retrieves windows font dialog box and used to set font for the
information will be displayed on the form.
vii. Control Box: This property determines whether the form contain control menu box at
runtime which is used to minimize, maximize or close the form.
The scale properties of the form are used to position the object or text in a form accurately.
It has 5 scale properties. They are: ScaleMode, ScaleWidth, ScaleHeight, ScaleLeft,
ScaleTop.
Ok Cancel
File Edit View Project Format Debug Run Query Diagram Tools Add- Help
ins
TOOLBOX WINDOW
Toolbar contains a set of tools that are used at design time to place controls on a form.
Using these controls, an interface between user and the application can be created.
It contains more than 20 controls.
FORM WINDOW:
PROPERTIES WINDOW:
Properties window displays the list of design time properties for the selected objects and their
current settings.
A property is a characteristic of an object such as size , caption, height, width, etc.
To view the properties window
View->Properties or Press F4 shortcut Key.
The project explorer displays a hierarchical list of the projects and all other elements contained in
the project.
The elements of the project explorer window are:
The form layout window decides in which position the form will be displayed at runtime.
It allows the user to visually position the forms at design time.
OBJECT BROWSER
CONTEXT MENU:
STANDARD TOOLBAR:
The standard toolbar contains buttons that are shortcut to some commonly used items.
Some of them are open project, save project, cut, copy, paste, etc.
Name:
It is used to specify a name for the form.
This property is used only in code.
It is used to identify an object.
Default value is “Form1”.
Appearance:
It is used to determine how the form looks on the screen.
It has two values.
1 3D(Default)
0 Flat
BorderStyle:
It determines the border style of the form.
It has six values. They are:
0. None
1. Fixed single
2. Sizable(Default)
3. Fixed Dialog
4. Fixed tool window
5. Sizable tool window
Caption:
Caption property sets the title of the form.
It is used to identify the form when it is minimized.
Control Box:
This property determines the whether the form contain control menu box at
runtime.
Used to minimize, maximize or close the form.
Form1
Ok Cancel
b) Text Box:
A TextBox control is used to accept input from the user and display output provided by
the application. Some general properties of the textbox are: name, text, maxlength,
multiline etc. TextBoxes can word wrap automatically.
Properties of TextBox
Enabled: Determines whether the TextBox can respond to user-generated events.
Locked: Determines whether the TextBox can be edited. You can prevent the user from changing
the content of the TextBox.
MultiLine: Indicates whether it can accept multiple lines of text.
Alignment: Aligns the text to left justify, right justify or center.
MaxLength: Sets the maximum number of characters that can be entered. If you want to set a
limit on the number of characters that the user can enter, you can do it very easily with the
MaxLength property.
PasswordChar: This property is useful for a password program. For example, if u enter '*' as a
value to this property, whatever character you type in, it will be shown as '*'.
ScrollBars: Says whether the TextBox has a scroll bar.
ToolTipText: Sets the text displayed when the mouse is paused over the control.
Events:
Text Box can recognize 23 events. Some of the important events are: GotFocus,
LostFocus, KeyDwn, KeyUp, KeyPress.
Locked: Determines whether the TextBox can be edited. You can prevent the user from changing
the content of the TextBox.
MultiLine: Indicates whether it can accept multiple lines of text.
Alignment: Aligns the text to left justify, right justify or center.
MaxLength: Sets the maximum number of characters that can be entered. If you want to set a
limit on the number of characters that the user can enter, you can do it very easily with the
MaxLength property.
PasswordChar: This property is useful for a password program. For example, if u enter '*' as a
value to this property, whatever character you type in, it will be shown as '*'.
ScrollBars: Says whether the TextBox has a scroll bar.
ToolTipText: Sets the text displayed when the mouse is paused over the control.
Events:
Text Box can recognize 23 events. Some of the important events are: GotFocus,
LostFocus, KeyDwn, KeyUp, KeyPress.
b). Labels:
Label is used to display information
It is also used to display text such as status messages and other program information.
Properties of Labels:
i. Caption: This property is used to change the text displayed in the label control.
ii. Alignment: This property is used to align the text in the label. It has three values: 0 – Left
aligned, 1-Right aligned, 2- Center aligned.
iii. Wordwrap: This property is used to resize the text entered in the caption property. If the
text exceeds the width of the label control, the text wraps to the next line. Its value is
either true/false.
iv. Autosize: This property causes the control to horizontally expand and adjust to the size of
its contents.
v. Borderstyle: The borderstyle property has two values 0 & 1. 0-No border (default);
1- Single border occurred.
6. Explain Command buttons and Message Boxes.
For command buttons- Refer Question No.8 in 5marks.
For Message Boxes Refer Question no 4(a) in Ten Marks.
UNIT-II
Two Marks
For Loop :
syntax : For exp =initial to end example : for i=0to10
<statements> msgbox “welcome to VB”
Next exp next i
Nested For :
syntax : For exp1= initial to end example : for i=0 to 10
<statements> print i
For exp2=initial to end for j=0 to 10
<statements> print j
next exp2 next j
next exp1 next i
Do-while :
syntax : do example : dim n as integer n=1
<statements> do
Loop While condition form1.print n
n=n+1
Loop while n<=10
Do-until:
Syntax : do example : do
<statements> form1.print n
Loop until condition n=n+1
Loop until n>=5
While :
syntax : while condition example : while n<=5
<statements> form1.print n
Wend n=n+1
Wend
SUBPROCEDURE FUNCTION
Sub Procedure is procedure that performs Function Procedure also perform some
some action. action but also returns some value to point
from which it was called
End Function
Example: Example:
1. Design a form and with their properties and coding to implement at least 5
numeric and date and time functions (Nov. 11)
Square root
Date value
Round - off
Time value
Exponential
(B) Rich text box :it supplied with most versions of visual basic. It is one of the most
useful control in toolchest. The rich text box is a custom control, we have need to add
it to the tool box. 1. Choose project/components to open the components dialog box
2. choose Microsoft RichTextBox Control6.0
The control lets you display text with multiple fonts and sizes without having to go out
and buy third party custom control. More ever it is not limited 32k characters like an
ordinary text box.
Properties :
selLength : returns set of chars selected
selStart : return set of starting char of selected text
selText : returns set of string that is selected
selColor : sets color to the selected text
selFontName: lets you change the font
selBold, selItalic, selUnderline, selStrikethru : set the font styles of the selected text
respectively.
selFontSize: let you change font size of the currently selected text
The common dialog control provides a standard set of dialog boxes for operations such as
opening and saving files, setting print options, and selecting colors and fonts. The control also has
the ability to display Help by running the Windows Help engine.
The common dialog control
The common dialog control provides an interface between Visual Basic and the procedures in the
Microsoft Windows dynamic-link library Commdlg.dll. To create a dialog box using this control,
Commdlg.dll must be in your Microsoft Windows \System directory.
You use the common dialog control in your application by adding it to a form and setting its
properties. The dialog displayed by the control is determined by the methods of the control. At
run time, a dialog box is displayed or the Help engine is executed when the appropriate method is
invoked; at design time, the common dialog control is displayed as an icon on a form. This icon
can't be sized.
The common dialog control allows you to display these commonly used dialog boxes:
Open
Save As
Color
Font
1. If you haven't already done so, add the common dialog control to the toolbox by
selecting Components from the Project menu. Locate and select the control in
the Controls tabbed dialog, then click the OK button.
VB
' Visual Basic
' Uses a SaveFileDialog component.
SaveFileDialog1.InitialDirectory = My.Application.Info.DirectoryPath
SaveFileDialog1.ShowDialog()
VB
' Visual Basic
' UsesPrintDocument and PrintDialog components.
PrintDocument1.DocumentName = My.Application.Info.DirectoryPath _
& "MyFile.txt"
PrintDialog1.Document = PrintDocument1
PrintDialog1.ShowDialog()
VB
' Visual Basic
' Uses the Help.ShowHelp method.
Help.ShowHelp(Me, "file://C:\Windows\Help\calc.chm", _
HelpNavigator.TableOfContents)
A list box control displays a list of items from which the user can select one or
more.
List boxes present a list of choices to the user.
By default, the choices are displayed vertically in a single column, although you
can set up multiple columns as well
2. Differentiate check box and option button?(n13)
In Check box, you can select multiple options. In option button, you can select one
option
Option buttons are circular and check boxes are square
3. What is control Array?(n11)
A control array is a group of controls that share the same name and type. They also
share the same event.
It has a one element and can grow to as many as your system resources and
memory permit, its size also depends on how much memory and windows
resources each control requires.
4. Write short notes a data grid?(a11)
It displays a series of rows and columns representing records and fields from a
Record set of Objects
The data grid control can be quickly configured at design time with little or no
code.
5. What are Arrays?(a13)
An array is a consecutive group of memory locations that all have the same name
and the same type
To refer to a particular location or element in the array, we specify the array name
and the array element position number
6. What are combo boxes?(a14)
A combo boxes combines the feature of textbox & list box.
This control enables the user to select either by typing the text into combo box or
by selecting an item from the list.
7. How to declare arrays?(a13)
An Array can be declared as follows
Dim [Preserve] var name (Subscript) [Type]
Dim syntax has the following parts
Part Description
8. Define record?(a12)
It used at module level to define a user-defined data type containing one or more
elements
It create record with type name as data type
9. Define Grid?(a13)
The grid is so important for accurately positioning controls, mastering it will help
you give your applications a finished, professional look. In order to control the grid, choose
Tools|Options (ALT+T, O), and then go to the General page on the Options dialog box. The four
properties you can control are described next.
10. What is a list?(a14)
A Set of sequentially indexed elements having the same intrinsic data type.
Each element of an array has a unique identifying index number. Changes made to
one element of an array don’t affect the other elements.
11. Why sorting is to be done?(n12)
In order, To arrange data & to retrieve data from memory easily, the data items
should be sorted
12. What is an upper bound and lower bound?(n15)
The upper bound is the highest values and the lower bound is the lowest values in
index values that can be used in functions
Those functions can be used with static arrays as well as dynamic arrays
13. What is a fixed array?(a11)
Memory allocation is fixed as the same when the program runs.
The array cannot be changed during runtime
Eg: Private a(13) as String
Hold only 14 characters
14. What is a preserve keyword used for?(n13)
Preserve Keyword is used to preserve the values in the array
even after the array has been eliminated
15. State any two differences between fixed and dynamic array?
FIXED ARRAY DYNAMIC ARRAY
Values cannot be changed during Values can be allocated during runtime.
runtime
Memory space is determined while Memory is allocated dynamically.
declaration.
16. What is dynamic array?(a15)
The array size can be changed during the runtime
Eg: Private a( ) as String
Dim no( ) as Integer
No = Inputbox(“How many no’s)
17. Define Searching?(a16)
It referred as to search a number or a string in a long list
There are numerous methods for searching. Binary search is one of them
18. Define Sorting?(a15)
Sorting is arranging data in order.
There are many different ways to sort the data.
There are four different methods for sorting, they are Ripple sort, Bubble sort,
Insertion sort and Shell sort
19. Define STR COMP (String Compare)?(n12)
Sometimes the user while evaluating a string it is to be determined whether the
string is less than, equal to (or) greater than, for that the string compare function is
used
Syntax: Str Comp (String 1, String2, Compare)
20. Define find method?(n14)
It searches the text in a Rich Text Box control for a given string
Syntax:
object.Find(string, start, end, options)
21. What is WITH STATEMENT used for?(a13)
Instead of using multiple periods for accessing, WITH Statement can be used.
Tthe WITH STATEMENT is a convenient method for quick access.
Note: Visual Basic generates an error if you attempt to use the Load statement with an
index number already in use in the array
Index Property (Control Array)
Returns or sets the number that uniquely identifies a control in control array. Available
only if the control is part of a control array.
object[(number)].Index
The Index Property syntax has these parts:
Part Description
Object Ian object expression that evaluates
Number A numeric expression that evaluates to an integer that
identifies an individual control within a control array.
Control Scenario: Adding and Deleting Controls in a Control Array
The control arayexample demonstrate how controls --- in this case, option button --- are
added and deleted at run time. The example allows the user to option buttons that change
the background color of a picture box.
Start with a form, and then draw a picture box, a label, two option buttons, and three
command buttons.
Events in the Control Array Application
Next, you need to add the event procedures for the option buttons and command buttons.
Start by adding the form declaration:
Dim MaxId As Integer
The Click event procedures is shared by all the option buttons:
Private sub optButton_Click(Index As Integer)
picDisplay.Backcolor=QBColor(Index+1)
End Sub
Name option buttons are added by the Click event procedure for the Add command
button. In this example, the code checks that no more than ten option buttons are loaded
before the Load statement is executed. Once a control is loaded, its Visible property must
be set to True.
Private Sub cmdAdd_Click()
If MaxId=0 Then MaxId=1 ‘Set total option buttons
If MaxId> 8 Then Exit Sub ‘Only ten buttons
‘allowed.
MaxId = MaxId + 1 ‘Increment button count.
Load optButton(MaxId) ‘Create new button.
optButton(0).SetFocus ‘Reset button selection
‘Set new button under previous button.
optButton(MaxId).Top=optButton(MaxID -1)._
Top +400
optButton(MaxId).Visible=True ‘Display new Button.
optButton(MaxID).Caption=”Option”&MaxId + 1
End Sub
Option buttons are removed by the Click Event procedure for the delete command button
Private Sub cmddelete_Click()
IF MaxId<= 1 ‘Keep first two buttons.
UnLoadoptButton (MaxId) ‘Delete last Buttons.
MaxId = MaxId – 1 ‘Decrement button count.
optButton(0).SetFocus ‘Reset button Selection.
End Sub
The Close button Click Event ends the application:
Private Sub cmdClose_Click()
End Sub
2. Col, Row
This property is return the row & column for the currently selected cell inside grid.
These properties are only available at run time.
Row = 0
Column = 0
Gives the location cell (0,0)
3. Col Position, Row Position
It is used to move through the whole rows & columns occasionally use.
Syntax
GridName col position(number)[=value]
GridName Row position(number)[=value]
4. colwidth,Row height
It specify the width of a specified column or height of a specific row
Syntax
GridName col width (colNumber%) = width%
GridName Row height (RowNumber%) = height%
6. Explain Insertion sort?(n12)
Insertion Sort
Check the new entry to the first entry.
Check backward if it fails move the whole entry down by one. So you have to move all
the entry.
Moving a “hole” along as it move to the list
Eg: Private Sub Insertion Sort (A$C)
Dim no of entries%, I%, J%, Temp$
No of entries% = UBound(A$)
For I% = 2 to no of entries%
Temp$ = A$(I%)
For J% = I% -1 To step – 1
If(Temp $ > = A$(J%) Then exit for
A$(J%+1) = AS(J%)
Next J%
A$(J%+1) = Temp$
Next I%
End Sub
If most of the time it moves objet ineffectively.
Private Errand$(13)
Or
Private Errand (13) As String
In the declaration section of the form This line of code sets up a one-dimensional will be array for
string that has 14 “pigeon holes” named Errand (0) through Errand (13) that will be visible to
every function or procedure on that form. The items would be stored in the Errands (0) through
Errand (13) pigeon holes.
To set up a dynamic one-dimensional array that will be visible to all functions or
procedures in the form, place a statement such as
Private Errand () As String
In the Declaration section of the form Notice the empty parentheses; this is what distinguishes a
dynamic array from a fixed array. (One reason that using empty parentheses for a dynamic array
is such a good notation is that it makes clear that the whole point of a dynamic array is to let the
situation determine the size.
Pass by values
When an argument is passed the original value will be retained evem after the program
terminates.
In VB, the pass by value will be stored in a temporary id for all variables that are
passed by value.
Example:
Sub Triple(No as Integer)
Num = 3 * Num
Print Num
End Sub
Form_Load( )
Dim Amt as Integer
Me : Auto redraw = true
Amt = 2
Print Amt
Triple (Amt)
Print Amt
TEN MARKS
2. Col, Row
This property is return the row & column for the currently selected cell inside grid.
These properties are only available at run time.
Row = 0
Column = 0
Gives the location cell (0,0)
3. Col Position, Row Position
It is used to move through the whole rows & columns occasionally use.
Syntax
GridName col position(number)[=value]
GridName Row position(number)[=value]
4.Col width, Row height
It specify the width of a specified column or height of a specific row.
Syntax
GridName col width (colNumber%) = width%
GridName Row height (RowNumber%) = height%
5.Text, Text Matrix
i) Text
Sets or returns the text inside the current cell.
ii) Text matrix:-
Set or retrieve the text in an orbitary cell without need to change the row & col proprerties.
Syntax:
Text matrix (row index, col index) = [String]
6. Cell width, Cell Top, and Cell left, Cell height.
This properties gives the size the location of a cell relative to it the container.
7. Alignment
Set the data alignment in a column.
Left – 0
Right – 1
Center – 2
8. Fixed Cols, Fixed Rows & Fixed alignment
By default zero rows and zero columns as a fixed and displayed in gray.
Fixed Alignment said to only the fixed row and fixed columns.
Syntax
GridName.fixedcols = Number of fixed cols%
GridName.fixedRows = Number of fixed Rows%
GridName.fixedAlignment = Setting Number%
9. Gridlines, scroll bars
This two properties control whether gridlines & scroll bar appear. (horizontal& vertical).
10. Left col, Top Row
It control which are left most column, highest row display from a grid.
2. What are list boxes and combo boxes? Differentiate them. Illustrate them with coding to
add and remove items in list and combo boxes?
List Box
List boxes when you have a fixed list of choice.
VB automatically add vertical scroll bar whenever is too small for all items it
contains
Combo Box
It combines the feature of text box & list box.
This control enables the user to select either by typing the text into combo box or
by selecting an item from the list
There are 2 types of combo box and which one get depends on the value of the
style property
1. If the value style property is said to the default value of zero
It will see the drop down, list of choice given in the box.
2. If the value of the style property of a combo box is one.
The user see the combo box with the list already drop down
0 – drop down
1 – Single combo
2 – drop down list
Generally,
Properties
I. Add item
II. Remove item
III. List
IV. Clear
V. List Amount
Unsupported Event
I. Double Click
II. Drop Down
III. Change Event
On Error GoTo line Enables the error handling routine that starts at line
specified in the required line argument. The line
argument is any line label or line number. If a runtime
error occurs, control branches to line, making the error
handler active. The specified line must be in the same
procedure as the On Error statement; otherwise, a
compile-time error occurs.
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 GoTowhen
accessing objects.
Remarks
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.
Disadvantage
The most of the time the comparison in the various loops of wasted.
Eg: Private Sub Ripple Sort (A$C)
Dim no of entries%, No of time%, I%, J%, Temp$
No of entries% = UBound(A$)
No of Time% = No of entries% - 1
For I% = LBound (A$) to no of times%
For J% = I% + 1 To No of entries%
If(A$(J%) < A$(J%) Then Swap A$(J%) A$(I%)
Next J
Next I
End Sub
Column Cell
In ms flex grid control in vb is used to create applications that present information in rows
and column. Display information in cell.
A cell is a location in ms flex grid at which row and column intersect cells can hold cells,
bitmaps or icons and some cells holding text and other having graphics.
The user can select a cell at run time by clicking it or by using the arrow keys.
But cannot edit or alter the cell contents.
It used to display and operates on a tabular data.
It allows complete flexibility to short, merge, format tables containing string and picture.
When bound to a data control MS Flex grid read only data.
General properties of flex grid
1. Cols, Rows
This properties determine the number of rows & columns in the grid.
They must be integer and the syntax is
GridName.cols = Num of cols%
GridName.Rows = Num of Rows%
Eg ;-frmDisplay.cols = 10
2. Col, Row
This property is return the row & column for the currently selected cell inside grid.
These properties are only available at run time.
Row = 0
Column = 0
Gives the location cell (0,0)
3. Col Position, Row Position
It is used to move through the whole rows & columns occasionally use.
Syntax
GridName col position(number)[=value]
GridName Row position(number)[=value]
4. Col width, Row height
It specify the width of a specified column or height of a specific row.
Syntax
GridName col width (colNumber%) = width%
GridName Row height (RowNumber%) = height%
5.Text, Text Matrix
i) Text
Sets or returns the text inside the current cell.
ii) Text matrix:-
Set or retrieve the text in an orbitary cell without need to change the row & col proprerties.
Syntax:
Text matrix (row index, col index) = [String]
6. Cell width, Cell Top, and Cell left, Cell height.
This properties gives the size the location of a cell relative to it the container.
7. Alignment
Set the data alignment in a column.
Left – 0
Right – 1
Center – 2
8. Fixed Cols, Fixed Rows & Fixed alignment
By default zero rows and zero columns as a fixed and displayed in gray.
Fixed Alignment said to only the fixed row and fixed columns.
Syntax
GridName.fixedcols = Number of fixed cols%
GridName.fixedRows = Number of fixed Rows%
GridName.fixedAlignment = Setting Number%
9. Gridlines, scroll bars
This two properties control whether gridlines & scroll bar appear. (horizontal& vertical).
10. Left col, Top Row
It control which are left most column, highest row display from a grid.
Example:
Dim myWeek, MyDay
MyWeek=Array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”sat”,”Sun”)
‘Return values assume lower bound set to 1 (using Option Base statement).
MyDay=MyWeek(2) ‘MyDay contains “Tue”.
MyDay=MyWeek(4) ‘MyDay contains “Thu”.
Syntax:
Dim varname[(subscripts)][As types]……
Where
1. Varname is the name of the variable.
2. Subscripts is the dimensions of an array variable; up to 60 multiple dimensions
may be declared.
3. Type is the data type of the variable.
Example 1:
Dim Number As Integer
Dim a(9) As Integer
Where a is an array variable it can store 9 integer values in the array.
Finds the Limits of an Array
LBound()
The Lbound function returns a long containing the smallest available
subscript for the indicated dimension of an array.
Syntax:
LBound(arrayname[, dimension])
Where
1. Arrayname is the name of the array variable.
2. Dimension is an whole number indicating which dimension’s lower bound is returned.
Use 1 for the first dimension, 2 for the second, and so on. If the dimension is omitted, 1 is
assumed.
Example:
This example uses LBound function to determine the smallest available subscript for the
indicated dimension of an array.
Dim Lower
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ‘Declare array variables.
DimAnyArray (10)
Lopwer=Lbound(MyArray, 1) ‘Returns 1.
Lower=Lbound(MyArray, 3) ‘Returns 10. 3 stands for the third dimension.
UBound
The UBound function returns a long containing the larghest available
subscript for the indicated dimension of an array.
Syntax:
UBound(arrayname[, dimension])
Where
1. Arrayname is the name of the array variable.
2. Dimension is a whole number indicating which dimension’s upper bound is returned. Use
1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is
assumed.
Example:
This example uses the UBound function to determine the largest available subscript for the
indicated dimension of an array.
Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ‘Declare array variables.
Dim AnyArray(10)
Upper=UBound(myArray, 1) ‘Returns 10.
Upper=UBound(MyArray, 3) ‘Returns 20.
Upper=Ubound(AnyArray) ‘Returns 10.
Reinitialize an array
Erase
The Erase statement reinitializes the elements of fixed-size arrays and releases
dynamic-array storage space.
Syntax:
Erase arraylist
Erase behaves differently depending on whether an array is fixed-size (ordinary) or dynamic.
Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as
follows.
Types of Array Effect of Erase on Fixed Array Elements
Fixed numeric array Sets each element to zero.
Fixed string array (variable Sets each element to a zero-length string(“”)
length)
Fixed string array(fixed length) Sets each element to zero
Fixed variant array Sets each element to Empty
Array of user-defined types Set each element as if it were a separate variable
Array of objects Sets each elements to the special value Nothing
Example:
The following example declares an array using the function and finds out the sum of the
values in the array.
General Declaration
Dim a(10) as integer
Private sub cmdget_Click()
Dim i as integer
For i = 0 to 9
a(i) = val(inputbox(“Enter a no.”))
next i
End Sub
Dim i as integer
Dim i as integer
For i= 0 to 9
s-s+a(i)
next i
msgbox “The sum of the array elements:&str(s)
End Sub
Fixed and Dynamic Arrays:
There are two kinds of arrays in Visual Basic: fixed arrays, where the memory allocation
stays the same for the whole time the program runs, and dynamic arrays, where you can change
size on the fly while the program is running. The advantage of a fixed array is that since memory
is set aside at the beginning of the program, you run a much smaller risk of running out of
memory while the program is running. The advantage of dynamic arrays is the flexibility they
give. You can change their sizes in response to what the program encounters. Both fixed and
dynamic arrays visible to the whole application, to a specific form or module, or only within a
function or procedure
To set up a fixed one-dimensional array visible throughout the whole form, place a
statement such as
Private Errand$(13)
Or
Private Errand (13) As String
In the declaration section of the form This line of code sets up a one-dimensional will be array for
string that has 14 “pigeon holes” named Errand (0) through Errand (13) that will be visible to
every function or procedure on that form. The items would be stored in the Errands (0) through
Errand (13) pigeon holes.
Static Arrays:
Static variables, it is occasionally useful to have an array whose contents remain the same
no matter how often the function or procedure is used. By analogy with static variables, this kind
of array is usually called a static array. To set up a static array inside a function or procedure, you
use the Static keyword:
Multidimensional Array:
Arrays with more than one dimension; they’re usually called multidimensional arrays. Just
as list of data lead to a single subscript (one-dimensional arrays), tables of data lead to double
subscripts (two-dimensional).
Dim LargeArray %( 2, 2, 2, 2, 2, 2, 2, 2)
Index ranges in multimensional arrays; you obviously need versions of LBound and
UBound. The commands
LBound (NameOfArray, I)
UBound (NameOfArray, I)
UNIT-IV
TWO MARKS
The Multiple Document Interface (MDI) was designed to simplify the exchange of
information among documents and all under the same roof. With an MDI application, we
can maintain multiple open windows, but not multiple copies of the application.
Data exchange is easier when we can view and compare many documents simultaneously.
An MDI application must have at least two forms, the Parent Form and one or more Child
Forms. Each of these Forms has certain properties. There can be many child forms
contained within the Parent form. The Parent Form may not contain any controls. The
parent Form can usually have its own menu.
We can use the Debug menu to gain access to the tools needed for debugging, and most of
the tools needed for testing and debugging can be found on the debug toolbar. Choose
View--->Toolbars--->Debug.
Usually the debugging tools are used when the program is in break mode. There are more
than 10 debugging tools available in Visual Basic. The first three tools are the most
common way of switching from project design mode to break mode.
Debugging Tools Keyboard Function of the Tool
Shortcut
Run/Restart F5/SHIFT+F5 Start the program as a new or restarts it
A dialog box is nothing more than a form with controls on it. We can add a new form to
any project (with Project | Add Form) and put any controls you want on the form. The
toolbox includes several file-related controls such as the File List Box control and the
Directory List Box control that we can place on the form.
The Common Dialog Box control, however, makes sure that our dialog boxes that
mimic those found in numerous other applications perform in the same way as those in
other applications. We want to present the same set of common dialog boxes that users are
used to seeing in other applications, or they will not adapt to our application as quickly as
they might otherwise. In addition, using the Common Dialog Box control and setting a
few properties is much simpler and gives us much more time than we would have if we
created these dialog boxes from scratch. Four methods of common dialog box control as
follows,
Color dialog box control
Visual Basic provides debugging tools to help the programmer track down such errors.
Program errors often do not prevent it from running, but may cause unexpected results.
The programmer’s interface to the debugging tools is via three debug windows. Such as,
Immediate window
Local window
Watch window
These windows can be accessed from the view menu or using the debug toolbar.
Debugging is carried out when the application is in break mode. Break mode is entered by
setting breakpoints, pressing Ctrl+Break keys.
5. Write short note on Immediate Window.
Most programming languages have a way to test program statements, procedures, and
functions. Visual Basic uses an immediate window with the results of a simple calculation.
We can use this window to test statements or to perform quick calculations when we are in
break mode.
If we type Print(?) 5 + 5 in the immediate window and press ENTER key, the Visual Basic
quickly responds with the answer 10 on the same immediate window.
The shape control has 20 properties. Usually, we can change them dynamically with code
while the application is running.
Setting of Shape effect Border style Fill style
property
6 - - Cross
7 - - Diagonal cross
We know how colors are assigned, and we can change the scale of our screen as we like to
fit. The syntax for this method is,
PSet(Col, Row)[, Color Code]
The PSet method doesn’t support named arguments. Since, the color code is optional. We
have to replace the parameters with the values we want. The values of the first entry are
column, and the second entry is row. After the VB process this statement, the pixel
defined by user will be printed.
For example, in the ordinary scale, using the default size for a form, the line is PSet(3722,
2212).
The objects that are usable in Visual Basic are collected into object(or type) libraries, for
example, Visual Basic’s object library, the Visual Basic for Applications object library,
Excel’s object library and so on.
An object library contains the information that Visual Basic needs to build instances of its
objects, as well as information on the methods and properties of the object in the library.
The object browser is the tool into the object libraries used in the project. To choose the
object Browser,
Select view/object browser
Press F2
Place some same type of controls (command buttons) on the form. Make their name
properties same and then a warning dialog box will come asking whether we want to
create a control array, click yes. Or after placing a control on the form, copy that and paste
on the form.
Set the index property of each control or we may not change as it is automatically set.
Now it is done. We are ready to use the control array in our code.
The line control has 15 properties. Usually, we change them dynamically with code while
the application is running. The most important properties for the line control at design
time are the BorderWidth property and the BorderStyle property.
BorderWidth determines the thickness of the line. It is measured in pixels and can range
from 0 to 8192. BorderStyle property of the Line control has six possible settings, but as
before only the last five are really useful.
The most important properties at run time for the line control are the X1, X2, Y1 and Y2
properties. The X1 property sets horizontal left end of the line, X2 property sets horizontal
right end of the line, Y1 property sets vertical top end of the line, Y2 property sets vertical
bottom end of the line.
Visual Basic let us execute one statement in our program at a time is called single
stepping. We have to press repeatedly F8 button or select the single step tool on the Debug
toolbar. It is one line of code at a time.
The first time we press F8 to start single stepping through our code, vb highlights the first
executable statement of the program in the code window and places a yellow arrow in the
leftmost column.
Debugging Tools Keyboard Function of the Tool
Shortcut
Single step (step F8 Moves through the program one statement at a
into) time
FIVE MARKS
1. Explain the importance of Testing.
With TestComplete we can easily test Visual Basic applications. We can perform any kind of
testing – unit, functional, regression and so on. The easiest way to create a test for the application
is to record a keyword test or a script routine. When playing back the test, TestComplete repeats
all the actions we performed during recording. If needed, we can also extend the recorded test
manually using a number of specific features provided by TestComplete.
When we record a test, we interact with the tested Visual Basic application as an end-user would:
navigate through the application’s screens, fill out forms and so on. TestComplete captures all
actions we performed in the application and adds them to the test.
A test consists of a sequence of operations that define various interactions with objects in the
tested application. For example, in the sample test below we can see that item selection from a
combo box is represented by the ClickItem operation, text input into text boxes - by
the SetText operation, and so on.
The recorded tests can be modified and enhanced in a number of ways to create more flexible and
efficient tests. For example, we can:
Insert checkpoints for verifying objects and values in the tested application.
Create data-driven tests that run multiple test iterations using different sets of data.
Refer to the following topics to learn more about creating and enhancing tests:
Testing Types
Keyword tests - visually configured tests with grid-based editing interface. Best suited for
novice users and those without programming knowledge.
Scripts - code written in one of the supported scripting languages. May be better suited for
advanced users.
We can select the test type when creating a test and cannot change it later. However, we can mix
keyword tests and scripts within the same test project and call them from each other.
TestComplete also includes additional test types, such as low-level procedures, unit
tests, distributed tests and so on. We can use them to address specific testing needs. However,
most automation is typically done using keyword tests and scripts.
2. Explain the concept of Debugging.
Debugging
Visual Basic provides many tools to help analyze how the code operates. These debugging
tools are particularly useful in locating the source of errors, or bugs. We can also use them to help
us to learn how code written by other people works. When we write the code, we will never be
able to create code that works first time round perfectly. Or if we do, if we change another section
of code, this may well affect code we have already written which then does not work. There are
generally three types of errors:
Run Time Errors
These occur while the application is running, when Visual Basic finds a statement that is
impossible to carry out, such as multiplying the contents of TextBox1 by 10 when textbox1
contains 'Hello'. If this error occurs when running Visual Basic, a dialog is displayed like the one
below. we are given the error number along with its message. We have the option to End the
current program, Debug the program which pauses the code, or to get help on that error.
Language Errors
These result from incorrectly structured code. For example, the Do statement without a
corresponding Loop statement, or an opening quote for a string, but no closing one. These sorts of
errors are picked out, either the moment we leave the line in the case of the missing quotes, or just
before the code executes in the case of the Do...Loop example.
Logic Errors
These errors occur when the code we have written does not run the way we expected it. No error
message is given as the code is using the correct syntax, and is not performing invalid operations,
however it is not giving the expected result. This is by far the hardest error to track down. Only by
going through the code very methodically and analyzing the results will be able to find the cause
(or by very good luck, but don't rely on it!)
The Common Dialog Box control is perhaps the most powerful control available because of
its capability to become one of several common dialog boxes we have surely seen in Windows
applications. The "List Boxes and Data Lists," we learned that the Combo Box control is
multifaceted because the control acts like one of three kinds of combo boxes, depending on
the Styleproperty we set. The common dialog box goes far beyond the combo box's capability to
take on different looks and purposes.
When we place a common dialog box on a form, we won't be able to resize it because the control,
like the Timer control, will not appear on the form at runtime, at least not right away. The runtime
code will have to display the common dialog box, and the look of the common dialog box
displayed depends on what our code needs at the time.
If we are going to work with a data file, we could display the File Open dialog box.
The quick viewer is a Windows application that pops up when we right-click a filename. The
quick viewer application displays the file in its native format without requiring us to own the
original format's parent application (such as Lotus 1-2-3).
We've seen the File Open dialog box in many Windows applications. The dialog box works just
as it does in Microsoft Word and other applications; the user can select a pathname or a filename,
change the view by clicking one of the View buttons, open the file as read-only so no changes are
made to the file, and even select another drive or computer to choose from by clicking the drop-
down list box.
The Common Dialog Box control creates the same File Open dialog box that we see in other
applications, in every respect. For example, we can right-click any folder or file displayed inside
the dialog box, and a pop-up menu appears with which we can rename the object, quick view the
object (if the system contains a quick viewer application for the selected file's type), open the
object, copy, cut, or perform a number of other tasks.
The Common Dialog Box control also presents a similar file-related dialog box, that produces a
File Save dialog box. The user will also be familiar with the File Save dialog box. Our application
can control the type of files displayed (by setting an appropriate filename extension type value)
and can respond to the user's selection.
We do not have to use the Common Dialog Box control. A dialog box is nothing more than a
form with controls on it. We can add a new form to any project (with Project | Add Form) and put
any controls you want on the form. The toolbox includes several file-related controls such as the
File List Box control and the Directory List Box control that we can place on the form.
The Common Dialog Box control, however, makes sure that our dialog boxes that mimic those
found in numerous other applications perform in the same way as those in other applications. We
want to present the same set of common dialog boxes that users are used to seeing in other
applications, or they will not adapt to our application as quickly as they might otherwise. In
addition, using the Common Dialog Box control and setting a few properties is much simpler and
gives us much more time than we would have if we created these dialog boxes from scratch.
Figure 12.3 shows another common dialog box that the Common Dialog Box control can
generate. Our applications can display the Color dialog box any time we want the user to select a
color for an application such as a drawing application. Windows supports several million colors,
and the Color dialog box shows only a few at a time. However, the user can locate the exact color
desired from the Color dialog box or define his or her own custom colors by clicking the dialog
box's Define Custom Colors button.
Figure 12.3 The Color dialog box is used by the user to pick a color.
The Font dialog box, shown in Figure 12.4, is another common dialog box that the Common
Dialog Box control can display for us. When the application works with text, we should give
which user the chance to select a font name or style. Our application cannot always know in
advance which fonts the user will have on his system. The Font dialog box will, however, give the
user a chance to select font information from his own computer. Once selected, the application
can use the user's selection values to generate the text in the selected font.
Figure 12.4 The Font dialog box shows font information from the user's system.
The Print dialog box, shown in Figure 12.5, displays a common printer dialog box that we can
display before printing any information to the printer. The dialog box returns information the user
selects about the pending print job. As with the other controls, the Print dialog box only returns
information to your application; it's up to your application to look at all relevant return
information and respond accordingly. Therefore, if the user elects to print six copies, your code
that follows the display of the Print dialog box must print six copies of the printed output.
Figure 12.5 The Print dialog box lets the user select a printer for output.
TIP
Want to add fax capabilities to your application? No problem; just display a Print dialog box. As
long as the user has installed a Windows-aware fax driver, such as WinFax Pro or Microsoft Fax,
the user can select that fax driver from the Print dialog box's Name list box. Your output, as long
as you set your application's printer to the user's selected value, goes to the fax machine instead of
to the printer.
CAUTION
The Print dialog box that appears on your system might be very different from the one shown
in Figure 12.5. All the Common Dialog Box control's dialog boxes display available information
based on their own computer settings. Therefore, your application will use these dialog boxes to
let the user select from the properties of his own computer, depending on how those properties
differ from yours.
The final dialog box that the Common Dialog Box control can display is a Help window, such as
the one in Figure 12.6. The Help window is linked to a help file that you generate. Generating
help files is not a trivial task, as you'll see in Hour 23, "Distributing Your Applications."
Therefore, this lesson doesn't show you how to connect a help file to your application. However,
the Common Dialog Box control's Help dialog box can produce the front-end dialog box your
user interacts with when you learn more about providing help in Hour 23.
An ImageList Control contains a collection of images that can be used by other Windows
Common Control, Such as ListView,TreeView,TabStrip and ToolBar controls.It does not appeare
on the form at run time. It serves as a container for icon that are accessed by other control such
as ListView,TreeView,TabStrip and ToolBar controls.
A ListView control displays data as ListItem objects. each ListItem object can have an optional
icon associated with the Label of the object.
1.Click on “Start” . Then select “All Programs, Microsoft Visual Studio 6.0 and Microsoft
Visual Basic 6.0.” .
2. Select “Standard EXE” from the list in the New Project dialog box and click
on“Open.” Click on “Project” on the menu bar, then select “Components” from the drop-down
menu.
3. Scroll down the list in the box until Microsoft Windows Common Controls 6.0 (SP4) is
visible. Click on the checkbox to select the component and then click on“OK.” All components
show in the Toolbox.
4. Choose the “ListView1” control from the list of controls in the toolbox. Place the control on
the form in Visual Basic.
5. Choose the “ImageList1” control from the list of controls in the toolbox. Place the control on
the form in Visual Basic.
The Shape control in Visual Basic 6.0 has no equivalent in Visual Basic 2008. However, you
can use Graphics methods to achieve the same results, or you can use the Visual Basic Power
Packs OvalShape or RectangleShape controls. These controls are available as add-ins.
Conceptual Differences
In Visual Basic 6.0, the Shape control provides an easy way to draw rectangles, circles,
and other shapes on a form at design time. The Shape control is a lightweight control, which
means that it does not have a Windows handle, also known as an HWnd.
In Visual Basic 2008, there is no equivalent for the Shape control, and lightweight controls are no
longer supported. However, there are ways to draw shapes on a form both at design time and at
run time.
Note:
You can download the Visual Basic Power Packs from the Microsoft Visual Basic 2005 Power
Packs page on the MSDN Web site.
At design time, you can draw a square or rectangular shape on a form by adding a Label control
and setting the Text property to an empty string, the BorderStyle property to FixedSingle, and
the BackColor, Width, and Height to the desired color and dimensions.
At run time, you can draw rectangles, ellipses, and complex shapes in a form's Paint event handler
by creating a new object from the Graphics class and calling its methods.
In Visual Basic 6.0, you can use a Shape control to draw a shape on top of a container control
such as a PictureBox or Framecontrol by adding a Shape control to the container.
In Visual Basic 2008, you can achieve the same effect by calling the Graphics methods in
the Paint event of the container control.
Project -> Add MDI form. Click Project from the menu bar, and click Add MDI form. It's simple!
Remember, a project can have only one MDI form.
Restrictions of the MDI form
1. You can have only one MDI form per project.
2. You can't place most controls on an MDI form. The only controls that can be
placed on the surface of the MDI form are Menus, Timer, CommonDialog, PictureBox,
ToolBar, and StatusBar.
These restrictions are there because MDI forms are the special type of forms, especially used to
handle multiple child forms.
How does the MDI form work?
There can be only one MDI parent form in a project with one or more MDI child forms (or simply
child forms).
MDI child form: To add a child form, you have to add a regular form, and set the
MDIchild property to True. You can have many child forms and can show an MDI child form
using the Show method.
AutoShowChildren property of an MDI form: The default value of
the AutoShowChildren property is True. When it is True, the MDI child forms are displayed once
they are loaded. When the value is False only then you can keep it hidden after loading, otherwise
not.
Restrictions of the MDI child forms:
1. You can't display an MDI child form outside its parent.
2. You can't display a menu bar on the MDI child form.
Now coming to the point - how the MDI form works. The parent form contains a menu bar on top
of it. From there, the user opens or creates a new document. In this way, the user accomplishes
his/her work in one or multiple documents, then saves and closes the document (form). You can
create instances of a single form in the code using the Set keyword (Using the object variables).
'Inside the MDIForm module
Private Sub mnuFileNew_Click()
Dim frm As New Form1
frm.Show
End Sub
ActiveForm property: This is the Object type read-only property of the MDI form. You
can apply this property to one of the children. For example, you can close the active form using
this property from the Close menu command of the menu bar.
'In the MDI form
Private Sub mnuFileClose_Click()
If Not (ActiveForm Is Nothing) Then Unload ActiveForm
End Sub
Note that '(ActiveForm Is Nothing)' represents that there is no active form. The 'Not' keyword
before it negates the value.
2. What are the common controls found in Visual Basic? Explain them.
Visual Basic (VB) has two types of Controls: Intrinsic Controls and Active Controls. These
controls represent all the Graphics User Interfaces, as well as Operating Systems resources,
available to programmers.
Intrinsic Controls
There are 20 controls which are built in to VB. These controls are called intrinsic controls.
Every one of the intrinsic controls are available to every VB program you write. When you create
a "New" VB project, all 20 of the intrinsic controls will show up in the Toolbox. This is true f
here are many free controls which can be used freely at design-time. However, commercial
controls require that you install them using a password before you can use them within your
project at design time. If you simply copy an OCX to your system and register it with
REGSVR32, don't be surprised if you get an error message when you try to put the OCX on a
form!
Intrinsic Control List
The following list shows the 20 intrinsic controls that come with all version of VB. I have a
separate tutorial section to discuss them further:
Horizontal Scroll
Database Features
Several of the intrinsic controls can display or edit data directly out of a database. With VB, the
ADO Data Control is used to access the database information and to distribute it on to the other
intrinsic controls which can handle database information. VB uses the terminology "databound"
to describe controls which have built-in features for handling database access.
Multi-processing: Timer Control
Timer is the most unusual of the intrinsic controls. By setting the .INTERVAL property this
control will automatically create an event on a regular basis. No other control does this!
Programmer can use it to create an action at a certain time and then turn the control off to prevent
repeats. Using multiple timers, an application can be multi-tasking.
As with the Intrinsic controls, not all of the ActiveX controls are equally useful. Some you will
use on many applications but you will use others only when you have a special need for the
features the controls offer.
When you start VB, none of the ActiveX controls are displayed in the Toolbox. Only the intrinsic
controls are displayed, so you must manually insert the ActiveX controls into the Toolbox as you
need them. To do so, right-mouse click on the toolbox and go to "Components", select the
controls to put on the toolbox and press "OK". All of the ActiveX controls are contained within
OCX files.
The Most Useful ActiveX Controls
These are the nine most used ActiveX controls:
Coolbar Progress Bar
ImageList Tabbed Dialog
Internet Transfer Control Tab Strip
ListView control ToolBar
Multimedia control
The Specialty ActiveX Controls
Some of the VB controls are very excellent tools for special system resource control, such as
Winsock in TCP/IP networking programming.
Communication control RichTextBox
Data Repeater SysInfo
MAPI Winsock
MSChart
More ActiveX Controls
Animation MonthView
DateTimePicker PictureClip
FlatScrollBar Slider
ImageCombo UpDown
MaskedEdit
Database Controls and ODBC
Database controls make database access very easy for programmers to utilize existing databases
in their applications.
Accessing Databases
Remember that there are a variety of database products on the market, and that many vendors
have their own proprietary formats in which the data is stored. In the case of Microsoft's Access
database program, the method of accessing the database is through software which Microsoft calls
its Jet Database Engine. Other vendors have their own access methods.
Many companies, including Microsoft, have provided their databases with the ability to be read
by software which uses a standard database manipulation method known as ODBC (Open
Database Connectivity). While a programmer can choose to let the VB database-aware controls
handle the details of accessing or manipulating databases (recordsets), it is also possible to use
code to create and edit databases.
DAO(DataAccessObject) The first method VB offered for using ODBC to create/edit databases
was DAO. It allowed the programmer to create a variety of objects in code, objects whose
properties and methods could be used by programmers to create/edit the databases. This worked
for Microsoft Access databases as well as any other ODBC-compatible database.
Microsoft also offered a second data access interface to ODBC which had some improved
features over DAO, but which also lost some of the more general capabilities of DAO. This
approach, called RDO (Remote Data Objects), primarily targeted the more complex aspects of
stored procedures and result sets. It is generally not used by most programmers.
ADO(ActiveXDataObjects) Microsoft is in the process of replacing the ADO/RDO features with
the newer ADO. ADO has a flatter model (meaning fewer objects) and is intended to be simpler
to use. In it's HELP files, Microsoft states that "ADO definitely represents the future of data
access technology"
For any programmer who simply wants to put a data control on a form and then display database
information in other controls, the choice of ADO/DAO/RDO is not critical because the controls
handle it for you, The advantage in manipulating databases in code is that you have a far greater
degree of control over what actions are performed against the databases.
VBDataControl VB provides two controls which makes the link to the database file and which
creates the recordset that is exposed to the rest of the controls in your application. The two are
identical in concept but differ in the flexibilty they offer to the programmer. I'll discuss the
common features first and then cover some of the differences.
The concept of a data control is pretty simple. Programmers set the .DataBaseName property to
tell the data control which database file to read. Then set a .RecordSource property to tell it which
table within the file to make available as a recordset to other controls. You can also create
recordsets which are combinations of one of more tables by setting the .RecordSource property to
an SQL statement.
For any controls which support databases, you set the .DataSource property to the data control
and the .DataField property to the specific field within the table/recordset that you want bound to
the control.
At that point the bound controls will display the information from the chosen field of the
recordset. If you make changes to the data then the database can be changed to reflect the changes
by either using the data control to move to a new record or by executing the .Refresh method of
the data control.
You can create entire database applications with essentially no coding, just the setting of control
properties.
You can set the .RecordSource to a command which tells the data control to create a recordset
that is a selected subset of the fields in one or more tables. And there is lot more that you can do
with SQL to reduce the amount of coding that you have to write yourself. Every VB programmer
should be familiar with the use of SQL to create/manipulate recordsets. SQL can even be used to
make mass changes to a recordset, including search and replace actions.
The two data controls :
Data control (intrinsic version)
This is the original, intrinsic version of the control. It supports the JET database engine
and can satisfy most beginners' needs.
This is the latest version of the data control, implemented as an ActiveX control.In line
with keeping your distribution files to a minimum, use the intrinsic control whenever
possible.
DataBoundControls Once you have the recordset available from the data control, you'll find VB
to have a rich variety of controls which can access the recordset. There are 7 intrinsic controls and
16 ActiveX controls which you have available to use. Each has its place and over time you'll find
yourself using most of them.
ComboBox
Here are the three versions that are available with VB, and some comments on how to decide
which one to use.
ComboBox
This is the original, intrinsic, version of the control. Use it whenever possible to keep
down the size of your application.
DataComboBox
This is Microsoft's most recent rendition of a combo control.
DBCombo
Left over from VB5, you can forego using this one in favor of the newer DataCombo
control.
List
Here are the three versions that are available with VB, and some comments on how to decide
which one to use.
ListBox
This is the original, intrinsic, version of the control.
DataList
This is Microsoft's most recent rendition of a list control.
DBList
Left over from VB5, you can forego using this one in favor of the newer DataList control.
Grid
There are actually four versions of a grid control that come with VB, but only three of
them can be databound. Here are the three versions and some comments on how to decide
which one to use or all versions of VB.
ActiveX Controls
Microsoft uses this terminology to refer to any control which exists as a separate file whose
extension is OCX. To use an ActiveX control in your VB program, the control must be registered
in the Windows Registry.
If you have a control which has not been registered by other software, you can register it yourself
using the free program provided by Microsoft. The program, REGSVR32, comes with all version
of Windows and is usually found in the Windows folder. To use it, simply type in:
REGSVR32 control.ocx
where the "control.ocx" is the filename of the control that you want to register.
IDE and Controls
Here's a key point to remember. Just because you register a control does not mean that you can
use the control in one of your projects. Registration only assures you that the control can by used
by an application at run-time. Whether or not a control can be used at design-time (within the
IDE) depends on the control.
A dialog box is a form defined with particular properties. Like a form, a dialog box is referred to
as a container. Like a form, a dialog box is mostly used to host child controls, insuring the role of
dialog between the user and the machine. Here is an example of a dialog box:
A dialog box has the following characteristics:
The only system button it is equipped with is Close . As the only system button, this
button allows the user to dismiss the dialog and ignore whatever the user would have done
on the dialog box
It cannot be minimized, maximized, or restored. A dialog box does not have any other
system button but Close
It is usually modal, in which case the user is not allowed to continue any other operation
on the same application until the dialog box is dismissed
2. From the Common Controls section of the Toolbox, click ListView and click the form
3. While the list view is still selected, in the Properties window, change the following
characteristics
(Name): LvwProperties
View: Details
4. Still in the Properties window, click Columns and click its ellipsis button
7. Click Add.
8. Click Add.
9. Click Add.
11. Click OK
ListView
13. To add another form to the project, on the main menu, click Project -> Add Windows
Form...
To create a dialog box, you start with a form, which you can get by creating a Windows
Application or deriving a class from Form. Here is an example:
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Text = "Domain Configuration"
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = FormStartPosition.CenterScreen
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
There are a few actions you should perform on a form to transform it into a dialog box; but
normally, these are only suggestions, not rules. Based on the Microsoft Windows design and
standards, to create a dialog box, you should set a form'sFormBorderStyle property
to FixedDialog. Setting this property changes the borders of the form to the standard borders of
a dialog box (the border of a dialog box is thinner than that of a regular form). You can set this
characteristic in the Properties window or programmatically. Here is an example:
Public Sub InitializeComponent()
Text = "Domain Configuration"
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = FormStartPosition.CenterScreen
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
End Sub
The Minimize and Maximize Boxes
Besides taking care of the border, you should also set both the MinimizeBox and
the MaximizeBox properties to False. This causes the window to display only the system Close
button. You can set these characteristics in the Properties window or programmatically. Here is
an example:
Public Sub InitializeComponent()
Text = "Domain Configuration"
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = FormStartPosition.CenterScreen
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
MinimizeBox = False
MaximizeBox = False
End Sub
1. To transform the PropertyEditor form into a dialog box, in the Properties window, change
its characteristics as follows:
FormBorderStyle: FixedDialog
StartPosition: CenterParent
MinimizeBox: False
MaximizeBox: False
ShowInTaskbar: False
TextBox TxtPropertyType
Label Bedrooms:
TextBox TxtBedrooms
Button OK BtnOK
Label Bathrooms:
TextBox TxtBatrooms
TextBox TxtMonthlyRent
When you create a Windows Forms Application, the starting form is made available to you. If
one form is not enough for your application, you can add as many as necessary. To add (or to
create) a (new) form, you have various options:
On the main menu, you can click Project -> Add New Item...
On the main menu, you can click File -> Add New Item...
In Solution Explorer, you can right-click the name of the project, position the mouse on
Add, and click Add New Item...
In the Add New Item dialog box and in the middle section, click Window Form (.NET), provide
a name in the Name edit box then click Open.
If your application is using various forms and you want to display a particular one at design
time:
In the Forms Designer, you can click the tab that corresponds to the desired form and that
has [Design]
On the main menu, you can click Window and click the name of the form in the list under
Close All Documents
In Solution Explorer, expand the Header Files node if necessary and double-click the
name of the desired form that has the .h extension
If you visually add two (or more) forms to your application, you may need to link them, allow
one to call the other. To do this, in the top section of the file, type #include followed by the
name of the header file in which the form was defined. In the section where you want to access
the form, declare a handle to the class of the form and use the new operator to allocate memory
for it. To display the other form, you can call its Show() method.
Working with graphics is easy in Visual Basic 6. VB6 gives you the flexibility and power to make
graphical applications in easy steps. It is rich in graphics related features. The built-in methods,
properties and events allow you to use these features most effectively.
In this tutorial, you will learn about various graphic methods, properties and techniques. The
graphic methods and properties let you perform some graphical operations. More specifically,
they allow you to draw points, lines, circles, rectangles, ellipses and other shapes. You will also
learn how to display text and images. Finally, this tutorial introduces you to the Paint event.
This tutorial is for the beginner learners. So the concepts are presented in the simplest way
possible. Code examples have been used wherever they became necessary.
Graphic methods
The graphic methods allow you to draw on the form and the PictureBox control. In Visual Basic
6, graphic methods are only supported by the form object and the PictureBox control. However,
the later versions of Visual Basic allow you to use them with other objects and controls.
First of all, the graphic methods in this section are discussed only to give you a basic idea about
them. Later in this tutorial, I will show you how to use them in your code to perform certain
operations like printing text, drawing shapes etc.
The-common-graphic-methods-are-explained-below:
Print: Print is the simplest graphic method in Visual Basic 6. This method has been used
throughout the earlier versions of the language. It prints some text on the form or on the
PictureBox control. It displays texts.
Cls: The Cls method is another simple graphic method that is used to clear the surface of
the form or the PictureBox control. If some texts are present, you can use the Cls method
to remove the texts. It clears any drawing created by the graphic methods.
Point: The Point method returns the color value from an image for a pixel at a particular
point. This method is generally used to retrieve color values from bitmaps.
Refresh: The refresh method redraws a control or object. In other words, it refreshes the
control. Generally, controls are refreshed automatically most of the times. But in some
cases, you need to refresh a control’s appearance manually by explicitly invoking the
Refresh method.
PSet: The PSet method sets the color of a single pixel on the form. This method is used to
draw points.
Line: The Line method draws a line. Using the Line method, you can also draw other
geometric shapes such as rectangle, triangle etc.
Circle: The Circle method draws a circle. Using the Circle method, you can also draw
other geometric shapes such ellipses, arcs etc.
PaintPicture: The PaintPicture method displays an image on the form at run-time.
TextHeight: The TextHeight method returns the height of a string on the form at run-time.
TextWidth: The TextWidth method returns the width of a string on the form at run-time.
The LoadPicture function
The LoadPicture function loads a picture to the form or to the PictureBox control. It sets the
picture to the control in order to display it. The function takes the file path as an argument. The
LoadPicture function allows you to set pictures at run-time.
Example:
Picture1 = LoadPicture(“C:\MyPic.JPG”)
Here, Picture1 is the PictureBox control. When this code is executed the picture is loaded and set
to the PictureBox control. If Visual Basic cannot find the picture in the specified location, it
throws a run-time error ‘53’.
The RGB function
The RGB function returns an integer, a color code which is used to set colors in Visual Basic
code. The RGB color code is a combination of red, green and blue colors. Consider the following
example to understand RGB function in VB6.
Example:
Form1.BackColor = RGB (120, 87, 55)
The RGB color is set as the background color of the form object. The first, second and the third
arguments represent red, green and blue colors respectively. The color value is an integer. These
values are in a range of 0 to 255. So you can use any value between 0 and 255 to obtain a color.
Graphic properties
The graphic properties are useful while working with the graphic methods. Some of the form's
properties and some of the PictureBox's properties are the graphics properties.
The common graphic properties are discussed in this section. You’ll learn more about them using
code examples later in this tutorial.
Consider-the-following-graphic-properties.
DrawMode: The DrawMode property sets the mode of drawing for the appearance of
output from the graphic methods. In the DrawMode property, you can choose from a
variety of values.
DrawStyle: The DrawStyle property sets the line style of any drawing from any graphic
methods. It allows you to draw shapes of different line styles such as solid, dotted, dashed
shapes etc.
DrawWidth: The DrawWidth property sets the line width of any drawing from any graphic
methods. While drawing shapes, you can control the thickness of the lines using this
property.
FillColor: The FillColor property is used to fill any shapes with a color. You may use the
symbolic color constants to fill your shapes. You may also use the color codes as well as
the RGB function.
FillStyle: The FillStyle property lets you fill shapes in a particular filling style.
ForeColor: The ForeColor property is used to set or return the foreground color.
AutoRedraw: Set the AutoRedraw property to True to get a persistent graphics when
you’re calling the graphic methods from any event, but not from the Paint event.
ClipControls: Set the ClipControls property to True to make the graphic methods repaint
an object.
Picture: The Picture property is used to set a picture. Pictures can be set both at design
time and run-time.
Run-time graphic properties
CurrentX and CurrentY are the run-time properties which are used to set and return the position
of a shapeorpointatrun-time.
CurrentX: The CurrentX property sets or returns the horizontal coordinate or X-coordinate
of the current graphic position at run-time.
CurrentY: The CurrentY property sets or returns the vertical coordinate or Y-coordinate of
the current graphic position at run-time.
Printing text
In this section, I will show you how to use the Print method to display text on the form or the
PictureBox control in various styles or colors.
Printing-on-the-form
The following code prints some text on the form.
Example:-
Private Sub cmdPrint_Click()
Form1.Print "Hello world"
Form1.Print "Welcome to Visual Basic 6"
Form1.Print "Visual Basic is awesome!"
End Sub
The above code can be written in the following way too.
Example:-
Private Sub cmdPrint_Click()
Print "Hello world"
Print "Welcome to Visual Basic 6"
Print "Visual Basic is awesome!"
End Sub
In the above code, the Print method is called without the object name. Here ‘Form1’ is the object
name. When you’re writing code inside the form module, you may omit the form’s name while
invoking its methods.
Output of code:-
Specifying-printing-positions
You can change the printing position from (0, 0) to other. Examine the following code.
Example:-
Private Sub cmdPrint_Click()
CurrentX = 500
CurrentY = 1000
Print "This is a new text"
End Sub
Output of code:-
Printing-a-customized text
You can display text using different styles, sizes and colors. Consider the following code
example.
Example:-
Private Sub cmdPrint_Click()
Form1.FontSize = 18
'Form1 object name is omitted
ForeColor = vbBlue
Font = "MS Serif"
Print "This is a new text"
End Sub
Output of code:-
Drawing points
This section shows you how to draw points using the PSet method and how to use the Step
keyword withthePSetmethod.
Drawing-points-using-the-PSetmethod
The Pset method allows you to draw a point. You need to specify the coordinate i.e. the drawing
position. You can also pass a color constant that is an optional argument in the PSet method.
Example:-
Private Sub cmdShow_Click()
DrawWidth = 10
PSet (100, 500)
End Sub
Output of code:-
Relative-positioning-with-the-Stepkeyword
The Step keyword allows you to draw in a position relative to the current position. See the
example.
Example:-
Private Sub cmdShow_Click()
DrawWidth = 10
CurrentX = 500
CurrentY = 500
PSet Step(0, 0)
End Sub
The above code draws a point in the (0, 0) position relative to the current position that is (500,
500).
That means, the point is drawn in the (500, 500) position. But this is (0, 0) position relative to the
current position.
Output of code:-
Drawing lines
The Line method lets you draw lines in Visual Basic 6. You need to specify the starting point and
the finishing point of the line in the argument. You may also specify the color of the line. This is
optional, though.
A-simple-line
The following code example shows how to draw a simple line using the Line method in Visual
Basic 6.
Example:-
Private Sub cmdShow_Click()
DrawWidth = 5
'A hyphen is required between the points
Line (0, 0)-(2000, 2000), vbBlue
End Sub
Output of code:-
A-line-with-drawing-styles
Form’s DrawStyle property lets you draw lines using a particular style. The constant values of the
DrawStyle property are 0 (vbSolid), 1 (vbDash), 2 (vbDot), 3 (vbDashDot, 4 (vbDashDotDot), 5
(vbTransparent) and 6 (vbInsideSolid). The default value is 0, vbSolid. You may use the numeric
constant or the symbolic constant such as vbSolid, vbDash etc to change drawing styles in your
code.
NOTE: The DrawStyle property does not work if the value of DrawWidth is other than 1.
Example:-
DrawWidth = 1
DrawStyle = 1
'A hyphen is required between the points
Line (0, 0)-(2000, 2000), vbBlue
DrawStyle = vbDashDot
Line (100, 900)-(2800, 2800), vbRed
Output of code:-
Drawing circles
You can draw a circle using the Circle method in Visual Basic 6. You may also use the Circle
method to draw different geometric shapes such as ellipses, arcs etc. You need to specify the
circle’s center and radius values to draw a circle using the Circle method.
A-simple-circle
The following code draws a simple circle using the Circle method in Visual Basic 6.
Example:-
Private Sub cmdShow_Click()
DrawWidth = 3
Circle (1800, 1800), 1000, vbRed
End Sub
In the above code, (1800, 1800) is the circle’s center, and the radius value is 1000. The color
constant ‘vbRed’ is an optional argument.
Output of code:-
A-circle-filled-with-color
The following code example shows how to fill a circle with color in Visual Basic 6.
Example:
Private Sub cmdShow_Click()
FillStyle = vbSolid
FillColor = &H80C0FF
DrawWidth = 3
Circle (1800, 1800), 1000, vbRed
End Sub
Output of code:-
Rectangle
The Line method can be used to draw different geometric shapes such as rectangle, triangle etc.
The following example shows you how to draw a rectangle using the Line method in Visual
Basic6.
Example:-
Private Sub cmdShow_Click()
DrawWidth = 3
Line (300, 300)-Step(4000, 2000), vbBlue, B
End Sub
The B argument in the Line method lets you draw a rectangle.
Output of code:-
Displaying an image
The LoadPicture function sets a picture to the PictureBox control or the form object. It requires
the file path as an argument. The following example shows you how to use the LoadPicture
function.
Example:-
Private Sub cmdShow_Click()
Picture1 = LoadPicture("D:\pic.JPG")
End Sub
Output of code:-
1. Select the menu item to which you want to assign an access key.
2. In the Caption box, type an ampersand (&) immediately in front of the letter you want to
be the access key.
For example, if the Edit menu shown in Figure 6.9 is open, the following Caption property
settings respond to the corresponding keys.
Cut Cu&t t
Copy
C&opy o
Paste &Paste p
Delete De&lete l
Select All Select &All a
Time/Date Time/&Date d
To assign a shortcut key to a menu item
To remove a shortcut key assignment, choose "(none)" from the top of the list.
Press CTRL+BREAK.
It's possible to break execution when the application is idle (when it is between processing of
events). When this happens, execution does not stop at a specific line, but Visual Basic switches
to break mode anyway.
You can also enter break mode automatically when any of the following occurs:
A statement generates a run-time error and the Break on All Errors error trapping option
has been selected.
A break expression defined in the Add Watch dialog box changes or becomes true,
depending on how you defined it.
1. Explain the methods available in the File operations with necessary example.
(NOV’11)
[ Ref. Question No. 9 in FIVE Marks]
Then VB automatically adds a class module to the project explorer window. Properties
window of the class module contains six properties. Important among those properties
are as follows:
i. Private
This is the default value. It indicates that other applications are
not allowed to access the information about the class, and cannot
create instances of it. Private objects are available within the current
project only.
ii. PublicNotCreatable
Other applications can use objects of this class. They cannot use
the CreateObject function or New operator to create objects. This is
helpful when a utility class is to be exposed and not to be modified
by others.
iii. MultiUse
This property allows other applications to create objects from
the class.
iv. GlobalMultiuse
It is same as MultiUse property, except that the properties and
methods of the class can be invoked if they were global functions.
It’s not necessary to create an instance of the class explicitly.
The following steps for creating and using DLL for adding two numbers are as follows:
(1) Once the class module is created in the ActiveX dll project, set the instancing the property
of the class into 6-GlobalMultiUse.
(2) Change the name of the project into any valid name, for example “Addition”
(3) Add the following code into the class:
Public Sub Add(X As Integer, Y As Integer)
Dim Z As Integer
Z = X + Y
MsgBox "Added Result : " & Z
End Sub
(4) Finally select “Make Addition.Dll” option from File Menu.
(5) Now, Open a new project and select “Standard.Exe” . Goto ProjectReferences select
“Addition” and click “OK” button.
(6) Write a click event on the form as shown below:
Private Sub Form_Click()
Add 10, 20
End Sub
(7) Now run the project. When the user clicks on the form add procedure will be called and
the result “30” will be displayed on the message box.
4. Explain about OLE automation (APR’13)
An object is a COM object implementing the IDispatch interface. Automation objects
are referred as ActiveX objects.
An application that manipulates an ActiveX object is referred to as an ActiveX client.
This interface exposes four methods. Invoke method allows calling methods of a class
by name, with a random number of parameters.
Most existing COM components are automation complaint which allow both late
binding and compile time early binding. This is achieved by implementing dual
interfaces, which are derived from IDispatch interface.
Late binding is slower and more reliable. For late binding, the client only needs to
know the name of the desired object and the names and parameters of methods it
actually uses.
For early binding. The client needs to know the complete definition and identifier for
every i8nterface requested.
Automation servers may be implemented as single-use or multi-use.
In single-use, each client connects to an individual instance of the server with an
individual instance of the class factory.
In multi-use, many clients connect to the server, sharing that server’s class factory
across all clients.
5. Explain the File System Controls in VB with examples. (NOV’13, APR’16).
File system controls in VB allow users to select a new drive, see the hierarchical
directory structure, or see the name of the files in a given directory.
File List box
A file list box displays the files in the current directory. It set the position, size,
color and font characteristics through the properties window or through code as
needed.
Properties:
Pattern - Pattern determines the files to be displayed in the file list
box. It can be set in the design time as well as runtime and allows
wildcard characters.
Path - Path property sets or returns the current path for the file list
box.
Events:
Click, DblClick, Gotfocus, Lostfocus, Dragover, MouseUp,
MouseDown, OLEDragOver,etc.
Example:
For I = 0 To File1.ListCount -1
Filenames$(I) = File1.List(I)
Next
Directory List Box
A directory list box displays the directory structure of the current drive.
Properties:
ListCount - This property returns the number of subdirectories in
the current directory.
Path - It returns the current path.
Events:
Click, DragDrop, DragOver, Gotfocus, LostFocus, OLEDragdrop, etc.
Example:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Drive List Box
Drive list boxes are pull down list boxes which displays the current drive.
When the user clicks on the arrow, VB pulls down a list of all the valid drives.
Properties:
Drive - Important property which sets or returns the current
drive.
Events:
Change, DragDrop, DragOver, GotFocus, Lostfocus, etc.
Example:
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
ChDrive Drive1.Drive
End Sub
6. How to monitor the activity of a mouse? Explain. (APR’14)
All controls in visual Basic are mouse sensitive. Every time if, the user uses the mouse a
mouse event is fired. Also a click event is fired if the user clicks the mouse. When the user double
clicks the mouse, a Dblclick event is fired. When the user presses a mouse button MouseDown
event is fired. When the user releases the mouse, a MouseUp event will be fired. Every time the
mouse moves, a MouseMove event occurs.
Most of the controls in VB support the mouse event procedure. Some controls such as
combo box have no support for the mouse events.
The various mouse event procedures are:
i) MouseDown – It occurs when the users clicks or press any of the mouse button.
ii) MouseUp - – It occurs when the users releases any one of the mouse button.
iii) MouseMove- – It occurs when the users moves the mouse pointer on the control or to
the blank area of the form.
All the mouse event procedures are of the same form and same parameters.
Sub ObjName_MouseEvent(Button as Integer, Shift as Integer, X as Single, Y as Single)
Syntax:-
Statements
End Sub
Examples:
Here,
ObjlName is the name of the Control from which the event is being fired.
Button is an integer which indicates the left, right or middle button of the mouse
Mouse Button Pressed Button Parameter
Value
Left 1
Right 2
Left & Right 3
Middle 4
Left & Middle 5
Right & Middle 6
All 7
Shift It is an integer which indicates whether the mouse is clicked along with the shift key,
ctrl key or Alt key.
X, Y X and Y co-ordinates of the current mouse position.
MouseDown:
MouseDown event is executed when the user clicks any mouse button. Example for
MouseDown event is as follows:
Private Sub Form_MouseDown(Button as Integer, Shift as Integer, X as single, Y as single)
Circle(X,Y), 75
End sub
The above example simply draws small circles at the mouse’s current location using the
circle method on the form. The parameters X,Y represents the center of the circle and the second
parameter 75 represents the radius of the circle in twips.
MouseUp:
The MouseUp event fired when the users releases any one of the mouse button. The below
example describes the functionality of a MouseUp event of the form.
Private Sub Form_MouseUp(Button as Integer, Shift as Integer, X as single, Y as single)
Dim c as Integer
Randomize
C=Int (15 * Rnd)
Fillstyle = 0
FillColor=QBColor(C)
Circle(X,Y),300
End sub
Private Sub Form_MouseDown(Button as Integer, Shift as Integer, X as single, Y as single)
Circle(X,Y), 75
End sub
MouseMove:
VB does not generate a MouseMove event for every Pixel. The number of events
generated will be limited by the software and hardware combination and its architecture. However
whenever the user moves the mouse, a MouseMove event is fired.
Example:
Private Sub CtrlNmae_MouseMove(Button as Integer, Shift as Integer, X as single, Y as single)
PSet(X,Y)
End Sub
7. Explain the Following:(APR’15)
a. File system Controls
[Ref. Question No. 5 in TEN Marks]
b. DLL Server.
[Ref. Question No. 5 in FIVE Marks]
8. Explain any five events/methods/properties used for drag and drop operation for controls.
(NOV’15)
The following table summarizes the events, methods and properties used for
dragging and dropping of controls.
Item Description
DragMode Property Allows automatic dragging (value=1) or manual dragging
(value=0)
DragIcon Property Set this to change from the gray rectangle to a custom icon
when dragging.
DragDrop Event Associated with the target of the operation. This is generated
when the source is dropped on the target control.
DragOver Event Associated with any control. The source control passes over
during dragging.
Drag Method Starts or stops dragging when dragmode is set to manual.