vb solved qusetion bank
TRANSCRIPT
-
7/28/2019 Vb Solved Qusetion Bank
1/46
Q: Discuss the salient features of visual basic environment.
Ans:
Defining IDE
IDE is an acronym for Integrated Development Environment. The IDE is the workbenchon which you make your programs in Visual Basic.
The Visual Basic IDE is a collection of menus, toolbars, and windows that make up yourprogramming workbench. Each part of the IDE has features that affect different aspects
of your programming activity. The menu bar lets you direct the overall activity and
management of your programming. The toolbar enables you to access much of the menubar's functionality through various toolbar buttons. Forms--the basic building blocks of
Visual Basic programs--are presented in a Form window. You use the ToolBox to add
controls to the forms of your project. The Project Explorer displays the projects on which
you're working, as well as the different parts of each of those projects. You browse andset a control, form, and module's properties within the Properties window. Finally, you
position and view a form or forms onscreen within the Form Layout window.
Toolbars in the Visual Basic IDE
Toolbars are collections of small iconic buttons that reside in a bar underneath the menubar. These buttons offer access to the most commonly used functions that you have in the
Visual Basic menu structure. Toolbars are useful because rather than nevigating menus
and submenus to do what you want, you click a specific button in the toolbar to call aspecific functionality in the Visual Basic IDE.
ToolTips
ToolTips are little windows that appear when you hold the mouse pointer over a control
or toolbar button for a few seconds. Inside these windows is some text that tells you what
the control or toolbar button is about.
Using the Debug Toolbar
You use the Debug toolbar to test your program and resolve errors that might occur.
Using the Edit Toolbar
You use the Edit toolbar when you're working with code in a Code window. The features
of the Edit toolbar are similar to those of the Edit menu. You can Cut and Paste text.You can manipulate the layout of your code and do text selection, searches, and
replacement. Also, you can use automatic coding features such as Quick Info.
-
7/28/2019 Vb Solved Qusetion Bank
2/46
An interesting VB IDE feature that the Edit toolbar uses is the Complete Word feature
(also trademarked by Microsoft as Intelli-sense). This feature automatically completes a
keyword for you. For example, if you were to type Ms into a code window and theninvoke the Complete Word feature, Visual Basic would complete the word as MsgBox,
an intrinsic Visual Basic function that displays a Windows message box. The Complete
Word feature is very useful for avoiding syntax errors due to misspelling.
Using the Form Editor Toolbar
You use the Form Editor toolbar to size, move, and align controls on a form. The Form
Editor toolbar has the same set of features as the Format menu.
You align and size multiple controls on a form with the Form Editor toolbar.
Using the Standard Toolbar
The standard toolbar is the central toolbar in the Visual Basic IDE. The standard toolbaroffers many features found in the File, Project, Debug, and Run menus.
The standard toolbar gives you fast access to often-used functionality and information.
ToolBox
Controls are the building blocks with which you assemble your Visual Basic program.
The ToolBox is a palette of controls, and you build your user interface by selectingcontrols from the ToolBox and placing them on your forms.
Some controls are built into Visual Basic and can't be removed from the ToolBox; thesecontrols reside within Visual Basic itself. These controls are known as intrinsic controls.
Others live outside Visual Basic and reside in files that end with the extension .ocx.These controls can be added and removed from the ToolBox.
This ToolBox shows both intrinsic controls and the extra ActiveX controls that ship with
Visual Basic 6.
Navigating Through the Form Window and Code Window
Just as controls are the building blocks that you use to assemble your Visual Basic
program, a Visual Basic form is the foundation on which you build with those blocks.Forms reside in the Form Designer window. You work in the Form Designer window to
add controls to your form.
The Form Designer window is where you create forms for your Visual Basic programs.
For each Form Designer window, you can also open a Code window. Code windows are
where you work with the Visual Basic code that you write "behind" your form. You open
-
7/28/2019 Vb Solved Qusetion Bank
3/46
a code window by double-clicking a form or a control on the form. You also can open a
code window by choosing Code from the View menu.
Project Explorer
The Project Explorer in Visual Basic 6 helps you manage and navigate multiple projects.Visual Basic enables you to organize multiple projects into groups called project groups.
You can save the collection of projects in your Visual Basic session into a project group
file. Project Group files end with the extension .vbg.
The Project Explorer is a hierarchical tree-branch structure. Projects are at the top of thetree, and the project parts (forms, modules, and so on) descend from the tree. If you want
to work on a particular part, you double-click the part to display it. If you want to see the
part in a particular view--say, a form in a Code window--you select the form by clickingit once. Then click the View Code icon at the top of the Project Explorer window .
You can work with multiple projects in the Project Explorer window.
Add a form from the Project Explorer
1. Position the pointer on the white area of the Project window (not over a form
or any other item on the tree view).
2. Right-click to display the Project Explorer context menu.
3. Choose Add and then Form.
You can add or remove projects, forms, and modules to or from the Project
Explorer by using its context menu.
Properties Window
Properties and values
The programming jargonor terminology for a property's setting is a property's value.
In the Properties window, you read, configure, and control the initial settings of the
ActiveX controls in your program. As you become more familiar with Visual Basicprogramming, a good portion of your time will be spent learning, setting, and
manipulating control properties. Because controls are the building blocks of Visual Basicprograms, the Properties window is an essential tool to master.
You set the attributes of a control with the Properties window.
Setting Form Position with the Form Layout Window
-
7/28/2019 Vb Solved Qusetion Bank
4/46
The Form Layout window enables you to set the runtime position of one or more forms
onscreen.
You position a form by moving its representation on the "computer screen" in the FormLayout window with your mouse. As you move the pointer over the small form in the
Form Layout window, the pointer changes into a four-directional, arrow-headed cross. Toposition the screen, hold down your mouse button and drag the form to where you want it
to be on the computer screen.
The Form Layout window lets you position one or more forms as they appear onscreen.
Viewing the IDE
MDI versus SDI
MDI stands for multiple document interface; SDI stands for single document interface. A
multiple document graphical user interface is one that allows you to view multiplewindows within a larger window--various Word document windows within the Word
application window, for example. A single document interface is one where all windows
appear independently of one another without the unification of a single parent window.
You can view the Visual Basic IDE in two ways: with the multiple document interface(MDI) or the single document interface (SDI). MDI view shows all the distinct windows
of the Visual Basic IDE as member windows within one large IDE window
In the SDI view, distinct windows of the Visual Basic IDE exist independently of each
other. There's no master window to contain and provide a unified feel to the IDE.
Q2. (a) what do you mean by variables and constants? Give the rules to define and use
them.
Ans:
Variable:
A Variable is an area that stores value during programs execution. This area has a name
i.e. a variable name and a value that varies from time to time. For example while
processing the salary of employee in an organization there can be a variable Emp-Name
used to store the names of employees. The value of this variable will vary while
processing salary for each employee.
Public intSalary As Integer
Constants
Constants are nonvariable variables. They resemble variables in the manner they aredeclared and assigned values. Unlike variables, the values they hold remain unchanged
-
7/28/2019 Vb Solved Qusetion Bank
5/46
during program execution. To create a constant , you use the Const statement with the
following syntax:
[Public / Private ] Const constname [As type] = expression
Const Demo as string=rockConst arr_counter as integer=30
Visual Basic provides many built-in constants that are useful with various statements. ToSee a list of the valid constants, display the object browser and select Constants in the
classes/Modules dropdown list box.
Variable Naming Convention
At the time declaring a variable, the following naming convention should be consideredfor naming a variable:
It must begin with letter
It cant contain an embedded period, spaces or other punctuation characters.
It cannot exceed 255 characters.
It must be unique within its scope.
Data Types
Some data types perform faster than others do. Strategies for using certain data types for
certain uses and avoiding general use of others are essential for making an application as
efficient as possible. A brief overview of the most commonly used Visual Basic DataTypes are discussed below.
Visual Basic recognizes the following six types of variables:
o Numeric
o String
o Boolean
o Date
o Object
o Variant
Numeric
Visual Basic supports the following types of numeric data types listed below: Integer
A variable defined to be of the Integer data type is a signed integer
that is two bytes in length. Thus the value can range from 32,768
to 32,767
Long Noteit.zip
-
7/28/2019 Vb Solved Qusetion Bank
6/46
Variables of data type long are also signed integers, except that
they are 4 bytes long. This gives them a range of 2,147,483,648 to
2,147,483,648
Single
Visual Basic provides several floating-point data types. The first,
the single data type is 4 byte value with range of 3.4*10-38 to 1.4*10-45 and 1.4* 10-45 to +3.4*10+38
Double
Whenever larger floating points values are required, the double
data type can be used. It takes 8 bytes to represent this variable andit should be used when a great degree of precision is required.
Currency
The Currency data type is an 8 byte number with fixed decimalpoint. It supports 4 digits to the right of decimal point 15 to the
left. It has been defined for monetary calculations.
Byte
The Byte data type stores an integer in the range of 0 to 255 in asingle byte. This data type is often used to access binary files,image files, sound files etc. This data type can also be used in
numeric calculations but the result should not be stored in another
Byte data type variable if it exceeds 255.
String
The string is a data type used to store alphanumeric data. It takes
one byte per character in the memory. The length of a stringvariable depends on whether the string declared is of fixed length
or variable length. A variable length string can store nearly 4
billion characters and the size of the variable varies as needed to
accommodate the values assigned to them.
The following assignments are all valid for a variable length string.
Dim Sampletxt As String
Sampletxt=DAV Institute Of management
Sampletxt=DAV
Sampletxt=
A fixed length can be declared as follows:
Dim As String * Where
is the name given to the variable
is the maximum number of characters that the variable can hold.
-
7/28/2019 Vb Solved Qusetion Bank
7/46
For example refer the code :
Dim txt1 As string * 35
Dim txt2 As string * 35
Dim txt3 As string * 35
Private Sub cmdClick_Click()
txt1 = DAVIMText1.txt = txt1
txt2 = DAV Institute of MGMT.
Text2.txt = txt2
txt3 = DAV Institute of management
Text3.txt = txt3
End Sub
Boolean
The Boolean data types stores True/False values. Visual Basic allocates two bytes to
this data type.Boolean variables are internally stored as integer that take the value
1(for True) and 0 (for False)
Boolean variables are declared as :Dim No as Boolean
Date
Date and Time values stored internally in a special format. It is a double-prcesion
number,integer part represents the date and the fractional part represents time. A
variable declared as date can store both dat and time values.e.g. Dim Trans_date As Date
Trans_date = 02/02/1998
Trans_Date = 09/23/98 15:03:05 am
Object Variables
An object variable refers to one of Visual Basics many objects , and it can be used to
access the actual objects. For example, a Form has two command buttons on it,Command 1 and Command2. These can be declared as two object variables:
Dim x As CommandBotton , y As CommandButton
-
7/28/2019 Vb Solved Qusetion Bank
8/46
Each of these two objects variables x and y , these can be manipulated just like
objects.For example refer the code below:
Private Sub Form_Load()
Dim x As CommandBotton, Dim y As CommandBottonSet x = Command1
Set y = Command2
x.Caption = OKy.Caption = Cancel
End Sub
VariantVisual Basic uses variant data type as the basis for the variables you create. The
variant is used most often to store numbers and strings, but it can store a variety ofother types of data.
Declaring Variables
Explicit Declarations
To declare the variable as Explicit Dim statement is used followed by the name of the
variable to describe what type of information will be stored within the variable, for
example:
Dim kms As Integer
Dim message As String
Implicit Declarations
In this type of variable declaration , whenever Visual Basic comes across an
undeclared variable type it creates new variant , the generic data type which canaccommodate all other data types.
For Example:
X = WelcomeThe sample code x contains the string value Welcome. Visual Basic automatically
creates x and selects a default data type for the variable.
Q3. (b) Write the steps to set a scroll-bar that facilitates a user to input a number in
the range 1-100
Ans:
-
7/28/2019 Vb Solved Qusetion Bank
9/46
Properties of Scrollbar to Set
Min : 1
Max: 100
Value: 1
Private Sub HScroll1_Change()Text1.Text = HScroll1.Value
End Sub
Q4. Illustrate the use of with and exit for statements of Visual Basic.
Ans:
To Exit directly from for loop the Exit statement is used.
Example: Exit For
-
7/28/2019 Vb Solved Qusetion Bank
10/46
Private Sub Command1_Click()
Dim t,I,p As Integer
I=InputBox(Enter the number for table generation:)
For t=1 to 10
If t=5 thenExit For
End if
P=i*tPrint I & * & t & = & p
Next t
End sub
The above example generates a multiplication table
With Statement
With statemnt is used to execute statements using a particular object. The syntax looks
like this:
With object
[statements]
End With
Private Sub Form_Load()With Label1
.Caption = "Say Hello, in ..."
.Font.Size = 10End With
With Combo1.List(0) = "French"
.List(1) = "German"
.List(2) = "Hawaiian"
.List(3) = "Hebrew"
.List(4) = "Italian"
.List(5) = "Japanese"
.List(6) = "Spanish"
.Text = "Language"
.Font.Size = 10
End With
-
7/28/2019 Vb Solved Qusetion Bank
11/46
With Text1
.Text = ""
.BackColor = &H8000000A 'Gray
.BorderStyle = 0
.FontSize = 14
End With
With Command1
.Caption = "Quit"
.Font.Size = 10
End With
End Sub
Private Sub Combo1_Click()
Select Case Combo1.ListIndex
Case 0Text1.Text = "Bonjour"
Case 1Text1.Text = "Guten Tag"
Case 2
Text1.Text = "Aloha"
Case 3
Text1.Text = "Shalom"
Case 4
Text1.Text = "Buon Giorno"
Case 5
Text1.Text = "Konichihua"
Case 6
Text1.Text = "Buenos Dias"
End SelectEnd Sub
Private Sub Command1_Click()End
End Sub
-
7/28/2019 Vb Solved Qusetion Bank
12/46
Q4. Write a program that finds the second largest element in the array, without
sorting
Q5. How will you build classes in Visual Basic ? discuss with an example.
Ans:
Object
An object is a self-contained piece of functionality that can be easily used, and re-used asthe building blocks for a software application.
Objects consist of data variables and functions (called methods) that can be accessed and
called on the object to perform tasks. These are collectively referred to as members.
Class
Much as a blueprint or architect's drawing defines what an item or a building will looklike once it has been constructed, a class defines what an object will look like when it is
created. It defines, for example, what the methods will do and what the membervariables
will be.
Defining a Visual Basic Class
Before an object can be instantiated we first need to define the class 'blueprint' for the
object. In this chapter we will create a Bank Account class to demonstrate the concepts ofVisual Basic object oriented programming.
Begin by starting Visual Studio and creating a new Windows Application namedvbObjects. Once the project opens, select theProject... menu and selectAdd class.... In
theAdd New Item dialog, name the new class file clsBankAccount.vb and click on the
Addbutton.
-
7/28/2019 Vb Solved Qusetion Bank
13/46
Visual Studio will now add a new tab to code area for the new class file containing the
following class declaration:
Public Class clsBankAccount
End Class
We have now defined a class. The next step is to add some functionality to the class.
Creating Visual Basic Class Properties
Class members or properties are essentially variables embedded into the class. Memberscan bePublic orPrivate.
Public members can be accessed from outside the object. Private members can only be
accessed by methods contained in the class. This is the key to what is called data
encapsulation. Object-oriented programming convention dictates that data should beencapsulated in the class and accessed and set only through the methods of the class
(typically calledgetters andsetters).
We can now extend our BankAccount class to add member variables to hold the account
name and number. True to the concept of data encapsulation we will be creating methodsto access these values later, so will mark them asPrivate:
Public Class clsBankAccount
Private strAccountNumber As String
Private strAccountName As String
Private intBalance As IntegerPrivate accountFee As Integer = 5
End Class
Now that we have defined the properties of our class, the next task is to define methods
that will give us access to our data.
Defining Class Methods
Since we have declared our class data properties to be private, we need to
provide methods which will give us access to those properties from our code. This isachieved using Get and Set methods. The syntax for get and Set methods is as follows:
Public PropertypropertyName()Asdatatype Get .... Code to return property value
End Get
-
7/28/2019 Vb Solved Qusetion Bank
14/46
Set(ByValvalueAsdatatype) .... Code to return property value
End Get
To demonstrate this we will add to our class to provide methods to get and set the
account number and name. Note that after you type in thePublic Property line of thedeclaration, Visual Studio automatically creates a template for the Get and Set methods,
which should be filled in as follows:
Public Class clsBankAccount
Private strAccountNumber As String
Private strAccountName As StringPrivate intBalance As Integer
Private accountFee As Integer = 5
Public Property AccountName() As String
Get
End GetSet(ByVal value As String)
End SetEnd Property
Public Property Balance() As Integer
GetReturn intBalance
End GetSet(ByVal value As Integer)intBalance = value
End Set
End PropertyEnd Class
Now that we have defined our getter and setter methods we can add our own method to
perform a task. This is the same as writing a Visual Basic function. The purpose of our
method will be to subtract the account fee from the current balance:
Public Function subtractFee() As IntegerintBalance = intBalance - intAccountFee
Return intBalance
End Function
When called, the above function subtracts the account fee from the balance, assigns the
new balance to the intBalance variable and returns the new total.
-
7/28/2019 Vb Solved Qusetion Bank
15/46
Now that we have added some functionality to our class it is time to instantiate objects
from this class blueprint.
Instantiating an Object from a Visual Basic Class
The process of creating an object from the class 'blueprint' is called instantiation.Essentially, you instantiate an instance of the class and give that instance a name by
which you will refer to it when accessing members and calling methods. You can create
as many object instances of a class as you desire. Objects are instantiated from a classusing the new keyword. Visual Basic provides two ways to instantiate an object from a
class. These two alternatives are known as late-binding and early binding.
Late binding occurs when the assignment of the object to the variable occurs at run-time
when execution reaches the code where the object is created. There are drawbacks to thisapproach in that any syntax checking is not performed until the application runs because
the compiler has no way of checking whether you are referencing valid class members,
resulting in potential run-time exceptions. Another disadvantage is that execution can beslowed when using late-binding since much of the work performed by the compiler when
using early binding has to be performed at runtime.
Late binding is achieved using the new keyword as follows:
Dim objBankAccount As Object
objBankAccount = New clsBankAccount()
Early binding, on the other hand, has none of the draw backs of late-binding. The
compiler performs syntax checks to ensure the object is being used correctly andexecution speed is increased because the binding takes place at compile time - not at run-time.
Early binding is performed as follows:
Dim objBankAccount As clsBankAccount
objBankAccount = New clsBankAccount
It is also possible to instantiate the object at the same time that it is declared:
Dim objBankAccount As New clsBankAccount()
Accessing Object Properties and Methods
Now that we know how to write a class and instantiate objects from the class, we now
need to know how to call the methods we created in the class. First, you will recall thatwe created Get and Set functions the data members of our class. Because we did this, we
-
7/28/2019 Vb Solved Qusetion Bank
16/46
can change and access these properties simply by referencing them as we would any
other property. For example:
Dim objBankAccount As New clsBankAccount()
objBankAccount.AccountName = "John Smith"
objBankAccount.Balance = 1230
MessageBox.Show(objBankAccount.AccountName & " has a balance of " &
CStr(objBankAccount.Balance))
The above code excerpt assigns values to the AccountName and account balance
properties of our object. It then references the properties in order to display a string which
reads "John Smith has balance of 1230" in a MessageBox.
We can also call our subtractFee() method as follows:
Dim objBankAccount As New clsBankAccount()Dim intNewbalance As Integer
objBankAccount.AccountName = "John Smith"objBankAccount.Balance = 1230
intNewbalance = objBankAccount.subtractFee()
MessageBox.Show(objBankAccount.AccountName & " has a balance of " &
CStr(objBankAccount.Balance))
The result will be a message which reads "John Smith has balance of 1225", since theaccount fee has now been subtracted from the balance.
Q6. What is debugging ? How does Visual Basic help in it?Ans:
DEBUGGING
No matter how carefully a programmer designs and codes application, the programs aresure to have a few errors. These errors are generally detected when the program is tested.
Debugging basically means finding and removing errors from the programs. These errors
in the program can be in their syntax or logic. Visual Basic not only assists us in tracingwhat is happening in the application while it is running, it also helps in diagnosing the
program errors as we write through its automatic syntax check and various other tools
which helps in remembering the keywords and syntax as we type the code.
-
7/28/2019 Vb Solved Qusetion Bank
17/46
To detect and correct logical errors VB provides tools that allows us to pause a running
application inspects its condition step through individual statements and procedure make
changes to variable and code and resume execution.
Break Mode
In Visual Basic you are primarily working in two modes: Design Mode and Run Mode.
Design Mode:
In this mode the code is created and edited and the effects cannot be checked until the
code is executed(run).
Run Mode: The Programs execution can be checked , but no changes can be made tothe code.
Break Mode: It halts the operation of an application and gives a snapshot of its condition
at any instant as the program is still active. Only its execution is temporarily suspended.All variables retain their values , properties and statements. In this mode , you can modify
an applications code or observe the applications interface condition, or determine theactive procedures that have been called or even change the program flow.
If visual basic encounters any of the below mentioned statements then it enters into breakmode:
1) Breakpoint
2) Stop Statement
Break Mode can be entered manually in several ways:
1) You press CTRL+BREAK
2) Select the Break button on the toolbar
3) Press F5 while your program is running
Setting Breakpoints
A breakpoint works as marker in the code that tells Visual Basic to suspend programexecution. By setting the breakpoint at a place makes it easy to investigate which line has
suspended the program execution. Breakpoints are temporary and are not preserved with
the code i.e. when you close the project after setting the breakpoints and then reopen theproject , then the breakpoints will be gone.
To set a breakpoint
1. Select new project from the file menu
2. Select standard EXE as project type
3. double click on the form
4. Select the forms paint event as shown in figure
-
7/28/2019 Vb Solved Qusetion Bank
18/46
5. Position the insertion point anywhere in the line of a procedure where the
program execution is to be halted.Lets say that you want to place it at a line
given below the code.
Print The loop is incremented for & y & times
Private Sub form_paint()
Dim x As String
Dim y As IntegerFor y = 1 To 5
x = InputBox("Enter your name below")
Print x
Print "The loop is incremented for " & y & "times"Next
Print
Print "loop is ended"
End Sub
Watch Statement
Watch Statement basically helps you to tell visual basic to observe a particular variable
and enter a break mode when a particular condition occurs.
The watch window helps in monitoring the behavior or expression as the programexecutes.
Adding a watch expression1. The following code already exists
Private Sub form_paint()Dim x As String
Dim y As Integer
For y = 1 To 5
x = InputBox("Enter your name below")Print x
Print "The loop is incremented for " & y & "times"
NextPrint
Print "loop is ended"
End Sub
-
7/28/2019 Vb Solved Qusetion Bank
19/46
2.
The immediate window
The immediate window is used to query variables and object
Property values, and to run the code. You can use the immediate window to testprocedures, evaluate expressions , or assign new values to variables or properties in thecode. The immediate window displays information that results from debugging
statements you have placed in the code or that you typing commands directly in the
window.
To evaluate expressions , you print the immediate window.:
1. In Break mode, enter print methods directly in the immediate window.2. Include Debug print statements in the application code.
The scope or the immediate window is limited to the current procedure only. This
includes only local variables declared within the current procedure, module variables
declared within the current code module, and gloabal variables. Any variables orproperties out of scope are not displayed
Debug.Print statement
-
7/28/2019 Vb Solved Qusetion Bank
20/46
The debug object s print method sends output to the immediate window without entering
Break mode.the following syntax is used , where the [items] is an expression or list of
expression to print if omitted, a blank line is printed.
Debug.print[items][;]
Locals Window
A Local window displays the current value of variables
Q7. How will you draw the following figure in Visual Basic?Ans:
Private Sub Command1_Click()
Picture1.Circle (1000, 1000), 800, vbRed
Picture1.Line (172, 1000)-(1800, 1000), vbRedPicture1.Line (1000, 172)-(1000, 1800), vbRed
Picture1.Line (1800, 172)-(1800, 2000), vbRed
End Sub
Q8. Write short notes on any two of the following:
(i) Database support in VB(ii) Recursion
(iii) Creating MDI applications.
Q9.(a) Explain all Object based features of VB.
(b) what is control array ? How is it created?
Ans:
Control Array
A Control Array is a group of controls that share the same name and type. They alsoshare the same event procedure. Acontrol array has at least one element and can grow to
as many elements as your system supports. The maximum index you can use in the
control array is 32767. elements of the same control array have their own proipertysetting and control arrays are used in menu control and option but on groupings.
-
7/28/2019 Vb Solved Qusetion Bank
21/46
The advantage of using control arrays is thet they need less resources than simply adding
multiple controls of the same type to form at design time. They are also useful if you
want several controls to share code.
At runtime , if you want to create control , then that control must be member of a control
array, each new element inherits the common event procedure of the array.
Creating a control array
There are three ways to create a control array at design time.
Assign the same name to more than one control.
Copy an existing control and then paste it onto the form.
Set index property to a value that is not null.
To add a control array to a form
1. Select the New Project from the File menu
2. Select standard.Exe project type.
3. Draw the TextrBox controls on the form as shown in figure:, the control will becomethe first element in the array.
4. Set the text boxs properties as follows:
Name Property to txtArrText Property clear Text1
Index property to no value
-
7/28/2019 Vb Solved Qusetion Bank
22/46
5. Select Textbox and press Ctrl+C or select Copy from the edit menu.
6. Click on the Form. Press Ctrl+V or select paste from the Edit menu. And place a
copy of textbox on the form.7. A dialog box appears to confirm whether you want to create a control array. Click on
Yes to create a control array.
8. Drag the new text box to a position directly below the original .9. Select the original text box and observe that the index property has changed from no
value to a value of 0.
10. Paste another copy of text box control on the form as shown in figure below.
Writing code for Control Arrays:
Private Sub txtarr_GotFocus(Index As Integer)
txtarr(0).Text = "Jyoti"
txtarr(1).Text = "B-12,Sec-20,Noida"
txtarr(2).Text = "U.P"
End Sub
Q10(a) How is an array declared in VB ? Explain the static and dynamic arrays in VB
Ans:
An array is a group of related data items that share a common name. These arrays may
contain the days of the week, months of the year, a list of valid employee numbers, or anyother group of related information. Let us consider the following situation:
-
7/28/2019 Vb Solved Qusetion Bank
23/46
We are provided with marks of 30 students. We wish to compute the average marks and
find out the number of students who have secured more than average marks. To find outthe number of students who have secured more marks than the average marks, we need to
compare all of the 30 marks with the average. We must therefore store marks in 30
different memory variable names such as mark1, mark2mark30. A neat and simplesolution to the problem is to define a single variable marks to store all the 30 marks. This
variable should refer to 30 values.
To declare an array in Visual Basic use the following statement
Dim x(5) as integer
In the above statement Dim is the keyword use for declaration
X(5) is the name of the array which can hold 5 values
All values are of integer type
In other words, Arrays are used to refer to a series of variables by the same name. They
use an index to refer to the individual elements. Some important points to be noted about
arrays are:All the elements in an array have the same data type.
We can declare an array of the fundamental data types i.e integer, float etc
Arrays are declared with DIM statement followed by the name of the array and the upper
bound in parenthesis. The upper bound cannot exceed the range of a LONG data type.
DIM PLAYER(10)
In the above example, PLAYER is the name of an array that can hold 11 elements. 11 isthe upper bound of the array and 0 is the lower bound of the array. By default, the lower
bound of an array is 0. Thus in the above example we have declared an array that
contains 11 elements (0-10).
Values can be assigned to the elements of an array as shown below:
Player(0) = RohitPlayer(1) = Anil
.
Player(10) = Rajiv
The keyword AS can be used optionally to specify the type of the arrays elements.
-
7/28/2019 Vb Solved Qusetion Bank
24/46
We can explicitly set the lower bound of the array .
DIM PLAYERS(1 TO 10) AS STRING
CLASSIFICATION OF ARRAYS
STATIC ARRAYS or FIXED SIZE ARRAYS: Those arrays which are always of the
same size and their size cannot be changed at run time
DYNAMIC ARRAYS: Those arrays whose size can be changed at run time.
CONTROL ARRAYS: The arrays which holds controls of visual basic are called Control
Arrays
Example of Static Arrays
Private Sub Command1_Click()
Dim marks(5) As Integer
For i = 0 To 5marks(i) = CInt(InputBox("Enter marks"))
Next i
End Sub
Q11. How are functions and subroutines declared in VB? Expalin with examples. Also
discuss different ways of passing of parameters.
What Are Subroutines
Subroutines can be thought of as miniature programs. A subroutine has a name
attributed with it, much like a variable does. Unlike a variable, a subroutine doesn't hold
data. Instead, it holds code. When the code in a subroutine is executed, the subroutine is
said to be "called". Therefore, one subroutine can "call" another subroutine. Somesubroutines are called automatically when certain actions are performed. For example,
the Form_Load subroutine is automatically called when a form loads. This is where you
have been inserting your test code before. What you were actually doing was adding codeto this subroutine.
Why Use Subroutine
You may ask yourself why subroutines would even be used. Why wouldn't you simply
put all of your code in one place? Subroutines are useful because they eliminateredundancy. Consider a complicated program like a word processor. When certain
-
7/28/2019 Vb Solved Qusetion Bank
25/46
actions are performed, such as closing the program, opening a file, or closing an
individual file, the word processor would probably check to see if you had modified your
document. If the user had modified the document since they opened it, the user would beprompted to save the file before performing the action. You could imagine that checking
if the document was modified, prompting the user, and acting on the input would require
many lines of code. If the programmer had literally typed this code into all of the placesin the program where this check was to be made, it would still work fine. However, what
would happen if the way the program handles documents changed, and therefore this
code needed to be changed? The programmer would have to change the code in everyplace where this check was made. Even worse, what if the programmer changed the code
in a few places but not in another? This would lead to bugs that are difficult to track
down. Instead, if this code was put in a subroutine, the subroutine would simply be called
from all of these places. If the code then needed to be changed, the programmer wouldonly have to change it in one place; inside the subroutine. By doing this, subroutines
eliminate redundant code, making the entire program easier to manage.
Creating A Subroutine
Creating a subroutine involves two lines of code. Luckily though, the Visual Basic codeeditor is smart, and will insert the second line for you! A subroutine begins with the word
"Sub", followed by a space, then a name identifying the subroutine. Two parentheses
follow, which are used for a parameter list. Don't worry about these yet, they will becovered later in the lesson.
Sub TestSub()
EndSub
After you enter the first line and press Enter, the second line will automatically be addedfor you. These lines represent the start and end of the subroutine. Any code inserted
between these lines will be executed when the subroutine is called. A subroutine can be
called in one of two ways: using the Call keyword, or by simply stating its name.
Sub TestSub()MsgBox "Code in TestSub()"
End Sub
Private Sub Form_Load()
MsgBox "Code in Form_Load()"
TestSub
MsgBox "Back in Form_Load()"End Sub
You can also use the Call keyword, as mentioned above:
Sub TestSub()
MsgBox "Code in TestSub()"End Sub
-
7/28/2019 Vb Solved Qusetion Bank
26/46
Private Sub Form_Load()
MsgBox "Code in Form_Load()"'This line is functionally equal as the line in the previous example
Call TestSub
MsgBox "Back in Form_Load()"End Sub
Subroutine Scope
The declaration of a subroutine has an optional keyword that can be used before "Sub".
You may enter a keyword representing scope here. "Private" and "Public" are examples
of scopes. You may have noticed that the Form_Load subroutine has the word "Private"before "Sub". This declares that this subroutine has a Private scope. If you don't specify
the scope of a subroutine, Visual Basic will use a default scope. You should never rely on
default scope, however. Get in the habit of always explicitly declaring the scope of your
subroutines.
What Is Scope
In the context of subroutines, scope represents where in your program the subroutine can
be called from. Subroutines with a Private scope can only be called from the source filefrom where they were defined. Subroutines with a Public scope can be called from
anywhere in your program. For example, a subroutine with a Private scope in a form can
not be called from another form, whereas it can if it has a Public scope.
Why Use Scope?
Why would you ever limit where you can call a subroutine from? Why wouldn't you
make all subroutines Public so that there are no limitations on your program? Subroutine
Scope is one of many tools that programmers can use to find bugs. If you know that yoursubroutine should never be called from a different source file, you should declare the
subroutine to be Private. This will prevent you from making a silly mistake and calling
this subroutine where it shouldn't be called. This will prevent mistakes that could be
extremely damaging and hard to detect. Instead, your program will crash with an errorrather than executing the subroutine with unpredictable results.
Parameters
Parameters, also called Arguments, are variables that can be "passed into" a subroutine. A
subroutine with parameters looks like this:
Private Sub DisplayAdd(x As Integer, y As Integer)MsgBox x + y
End Sub
-
7/28/2019 Vb Solved Qusetion Bank
27/46
Private Sub Form_Load()
DisplayAdd 5, 2
End Sub
A new subroutine has been declared called DisplayAdd. This declaration is different than
the declarations that you have seen so far, however, as code has been added between theparenthesis. From your knowledge of variables, this syntax should look somewhat similar
to you. x As Integer and y As Integer appear to be variable declarations without
the "Dim" keyword. These declarations are separated by a comma. These variables are
the Parameters for the DisplayAdd subroutine. Code within the subroutine can access x
and y as usual, as if they were normal variables. However, when the subroutine is called,the calling subroutine will also provide values for these parameters. Therefore, the
subroutine has now become dynamic. The code can act on input without caring where the
input came from. When the Form_Load subroutine calls DisplayAdd with the parameters5 and 2, the code within DisplayAdd is executed. The first line adds x and y together and
displays the result. x and y have already been filled with the values 5 and 2 from the
Form_Load subroutine. The calling subroutine doesn't have to use numeric constants,however. It can use variables as well:
PrivateSub DisplayAdd(x AsInteger, y AsInteger)
MsgBox x + y
EndSub
PrivateSub Form_Load() Dim a AsInteger
Dim b AsInteger
a = 5
b = 2DisplayAdd a, b
EndSub
This code has identical results. Note that DisplayAdd cannot access a and b. As far as
DisplayAdd is concerned, a and b are represented as x and y. Attempting to access a or bfrom DisplayAdd would result in an error.
ByRef and ByVal
Parameters can be sent to a subroutine By Reference (ByRef) or By Value (ByVal).
ByRef is the default, and means that changes to the variable in the subroutine will resultin changes to the source variable outside of the subroutine. ByVal literally copies the
values of the variables from the calling subroutine into the called subroutine. By doingthis, the variables can be changed, but their values will not change outside of the calledsubroutine. ByVal can also be a lot slower with large variable types, however, since
memory has to be copied from one location to another. If you don't have any reason to do
so, there is no need to pass variables ByVal. You can explicitly state the way that a
variable is passed to a subroutine by using these keywords before the variable name.Using the ByRef keyword, one could write a Swap function, which switches the values of
2 variables.
-
7/28/2019 Vb Solved Qusetion Bank
28/46
PrivateSub Swap(ByRef x AsInteger, ByRef y AsInteger)
Dim temp AsInteger
temp = xx = y
y = tempEndSub
Private Sub DisplayVals(ByRef a As Integer, ByVal b As Integer)
'Don't worry about understanding the next line yet, it will be explained laterMsgBox "a = " & CStr(a) & vbCrLf & "b = " & CStr(b)
End Sub
Private Sub Form_Load()Dim a As Integer
Dim b As Integer
a = 10b = 12
'Display values, swap, and display again
DisplayVals a, b'The next line is functionally identical to "Swap a, b"
Call Swap(a, b)
DisplayVals a, bEnd Sub
Notice that Call was used instead of simply stating the subroutine name. When using the
Call method however, you must use parenthesis when calling the subroutine. Note that
this program would also have worked without typing "ByRef" anywhere, since it is thedefault. The ByRef and ByVal keywords are rarely used in simple programs, however,
but it's a nice trick for your toolkit.
Functions
Subroutines have a close cousin called Functions. Functions are basically the exact same
as subroutines, except that they return a value. That means that the function itself has atype, and the function will return a value to the calling subroutine based on the code that
it contains. An example of this would be a function that adds two numbers, shown below.
A function is declared the exact same way as a subroutine, except using the "Function"keyword instead of "Sub". To return a value, assign a value of the proper type to the
function's name, as if it were a variable.
Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Dim Res as integerRes = x + yAdd = Res
EndFunction
Private Sub Form_Load()
Dim a As Intege
-
7/28/2019 Vb Solved Qusetion Bank
29/46
Dim b As Integer
Dim c As Integer
a = 32b = 64
c = Add(a, b)
MsgBox ("Sum is : " & c)End Sub
Functions Or Subroutines
The best way to determine which is better for your application is by asking yourself a
simple question. Will you need to return a value? If so, use Functions. If you don't, use
subroutines.
Q12. Discuss important events , VB statements and methods with respect to form object.Also discuss the various parts of MDI form.Ans: Given in Question bank
Q13. discuss the following basic Active-X controls in VB with suitable examples:
(a) Scroll Bar control
(b) Image Control command button.Q14. Write Short notes on the following :
(a) OLE
(b) DLLAns: Given in Question bank
Q15. Write a program in VB that draws a diamond, an arrow , a box and an oval on the
form.
Q16. Discuss error handling statements and objects in VB briefly.
Ans: Given in Question bank
Q17. What are the different ways to organize data files in VB ? Explain different modesand I/O statements for handling data files.
Ans: Given in Question bank
Q18. what do you mean by data controls ? How are these used to access database ? writeall steps.
Ans: see also in question Bank
Database Management
-
7/28/2019 Vb Solved Qusetion Bank
30/46
A database can be viewed as a set of interrelated data. Databasemanagement deals with the storage, retrieval and editing of the data withinthe database. One of the most important functions of Database managementis the Database security and Database validations.
Visual Basic makes it simple by supplying a variety of tools and approaches
for data management. For significant database applications, utilizingdatabase functionality that already exists becomes necessary. Visual Basic6.0 provides full-fledged database engine called Jet. This engine containsvirtually all the database functions that applications may need. The simplestand easiest way to access the Jet database engine is through bound datacontrol.
Data Access Object (DAO) has been the standard database access method forVisual Basic programmers. DAO was the first database interface includedwith Visual Basic in its third version.
Remote Data Object (RDO) was then introduced to make data-access moreflexible and functional in VB 4. The most recent release by Microsoft with
Visual Basic is the ActiveX data object, which is in a short while going to takeover all the other methods of data access.
Data Access Object
Data Access Object enables you to use a programming language to accessand manipulate data in local or remote databases and to manage databases,their objects and their structure. DAO utilizes Microsofts Jet database engineand can be used to access a wide variety of database formats, including,ISAM (Indexed Sequential Access Method) and Text.
In addition to this, DAO can also make use of Open Database Connectivity
(ODBC) databases through its ODBC Direct Object Model.Generally ODBC is a special technique to access a database residing on aseparate Server such as Informix, Oracle etc.
The DAO object model has 17 types of objects like Databases, RecordSets,Fields etc. Databases are accessed by opening an existing Database objector creating a new one. The individual fields in a table make up a RecordsetsField object and table of a database is held in a Recordset Object.
Data Access object is implemented through an ActiveX control called theData Control. This allows a large amount of DAOs power to be utilizedwithout having to add a single line of code. When used in conjunction with
Data aware controls such as TextBox, DBList, DbCombo, DbGrid etc, the Datacontrol becomes very powerful.
Information from a database table is fetched by the DAO and then supplied tovarious Data aware controls like TextBox, DBListBox etc.
Databases accessible through the DB Engine are FoxPro 2.0 to 3.0 and VFP,dBase III, IV and 5.0, Paradox 3x, 4x and 5x, Microsoft Access 1x to 3x, ODBCdatabases, Microsoft Excel 3.0 to 8.0, Lotus 1-2-3, WKS, WK1, WK3 and WK4,ASCII tabular Format, HTML Tabular Data and Microsoft Exchange 4.0 The
-
7/28/2019 Vb Solved Qusetion Bank
31/46
DBEngine consists of several Dynamic Link Libraries that are linked to yourVisual Basic program at runtime. DBEngine is controlled by our applicationthrough DBEngines object classes, their methods and properties.
Data Binding
In order to display the values of the columns accessed by the Data Control,some controls are required which support the data control. These control arecalled Data Bound controls and are simpler to use e.g., TextBox, LabelDBGrid, DBList etc.
These controls have basically two standard properties other than their regularproperties. The DataSource property enables you to specify the name of theData Control to which the client control will bind. The name of the DataControl(s) available on your form is already present in the dropped downCombo Box of this property in the property window.
The Datafield property, a string property of the Client Control, specifies whichof the Database field names available from the data control the client willbind.
After the DataSource and Datafield properties are set, the Data Control isproperly initialized, the Client Control automatically displays the contents ofthe bound field as the data control is used to navigate though the recordset.
You can then use an appropriate editable control, such as the textox, tochange the Data contained in the Bound field. DBCombo and DBlist enableyou to use the data control to provide a list of valid choices for a field, as wellas to bind the client control to a specific field.
Data Control and The Data Bound Controls
Visual Basic provides many sources to connect to a data source. DataControl is one of them. Data Control was the first medium to connect theapplications to a database in the third version of Visual Basic.
The Data control is an excellent tool for rapidly developing a databaseinformation retrieval system. With very little code you can get a useful viewinto stored information. This is practically a drop-in-place process where byyou can place a data control, A DBGrid and a Command Button on a form andbe able to access your database in a matter of minutes. After you setproperties your application is set to go.
Data Control
Data Control is one of the easiest modes to access databases. You canperform most data access operations using the Data control without writingany code at all. Data-aware controls bound to a Data control automaticallydisplay data from one or more fields for the current record or, in some cases,for a set of records on either side of the current record. The Data controlperforms all operations on the current record.
-
7/28/2019 Vb Solved Qusetion Bank
32/46
If the Data control is instructed to move to a different record, all boundcontrols automatically pass any changes to the Data control to be saved inthe database. The Data control then moves to the requested record andpasses back data from the current record to the bound controls when itsdisplayed.
The Data control is itself smart enough to handle a number of contingenciesincluding empty recordsets, adding new records, editing and updatingexisting records, and handling some types of errors. However, in moresophisticated applications, you need to trap some error conditions that theData control cant handle. For example, if the Microsoft Jet database enginehas a problem accessing the database file, doesnt have permission, or cantexecute the query as coded, a trappable error results. If the error occursbefore your application procedures start or due to some internal errors, theErrors event is triggered.
Data Control in Action
Using the data control
The data control is an intrinsic control used to bind that is, create aconnection- between a database and control such as text boxes. A databaseis sent to data control via its properties. Then individual control is bound todata control.
To add a data control to a form:
1. With a form open, double-click the data control in the toolbox (Figure9.1). The data control is placed on the form (Figure 9.2).
Figure 9.1
-
7/28/2019 Vb Solved Qusetion Bank
33/46
Figure 9.2
2. Using the properties window, change the caption of the data control tosomething descriptive, such as click here to control data display (Figure9.3).
Figure 9.3
Figure shows navigation buttons that are build into the data control.
To connect the data control to a base
1. With the data control open in the properties windows, select the database name properties in the left column (figure 9.4)
Figure 9.4
2. Click the ellipsis in the right column. The data base name dialog open(figure9.5)
-
7/28/2019 Vb Solved Qusetion Bank
34/46
Figure 9.5
3. From your file system, select the database.
4. Click open.
Figure 9.6
The data base file now appears in the right column of the properties windows(figure 9.6). The sample biblio.mdb database is shown in the figure.
Tips
Visual basic is often used with Microsoft access databases. Access
databases file have the .mdb suffix. Visual basic ships two sample access databases- biblio.mdb and
Nwind.mdb- for you to experiment with. You can find these databases inyour visual basic home directory.
Data control properties assignments can also be made in code. Biblioconsists of publisher, author, and book table. Nwind is an inventorydatabase of fictional food- trading company
End of File and Beginning of File Actions
The Data control can also manage what happens when you encounter aRecordset with no records. By changing the EOFAction property, you canprogram the Data control to enter Addnew mode automatically. Theseproperties have been discussed later.
Alignment
You can program the Data control to automatically snap to the top or bottomof its parent form by using the Align property. In either case, the Datacontrol is resized horizontally to fill the width of its parent form whenever the
-
7/28/2019 Vb Solved Qusetion Bank
35/46
parent form is resized. This property allows a Data control to be placed to anMDI form without requiring an enclosing Picture control.
Data Binding
In order to display the values of the columns accessed by the Data control,some controls are required which support the data control. These controlsare called Data Bound controls and are simpler to use e.g., TextBox, Label,DBGrid, DBList etc.
These controls have basically two standard properties apart from theirregular properties. The DataSource property enables you to specify thename of the Data Control to which the client control will bind. The name ofthe Data Control(s) available on your form is already present in the dropdown Combo Box of this property in the property window.
The Datafield property, a string property of the Client Control, specifieswhich of the Database field names available from the data control, the clientwill bind.
After the DataSource and Datafield properties are set, the Data Control isproperly initialized, the Client Control automatically displays the contents ofthe bound fields as the data control is used to navigate though the recordset.
You can use an appropriate editable control, such as the TextBox, to changethe data contained in the bound field. DBCombo and DBList enables you touse the data control to provide a list of valid choices for a field, as well as tobind the client control to a specific field.
Properties of The Data Control
BOFAction and EOFAction Properties
As discussed earlier the BOFAction and EOFAction properties return or set avalue indicating what action the data control takes when the BOF or EOF isencountered by Data control.
Syntax:
DataControlName.Recordset.BOFAction = value
DataControlName.Recordset.EOFAction = value
Different settings for the properties are :
Constant Value Description
VbBOFActionMoveFirst 0 Moves the record pointer back to the firstvalid record.
VbBOFActionBOF 1 Causes a validation event on the firstrecord, repositions
to the first record.
Above given values are for the BOFAction property, values for EOFActionproperty are :
-
7/28/2019 Vb Solved Qusetion Bank
36/46
Constant Value Description
VbEOFActionMoveLast 0 Moves the record pointer back to the lastrecord.
VbEOFActionEOF 1 Causes a validation event on the lastrecord, repositions to the last record.
VbEOFActionAddNew 2 After moving past the last record, triggersan AddNew event after Validation event.
Connect Property
The Connect property sets or returns a value that provides information aboutthe source of an open connection, an open database, a database used in apass through query, or a linked table. This property is read/write fordatabase objects, new connection objects linked tables and tabledef objects.
This property is read only for Querydef objects and basic tables.
Syntax :
Object.Connect = databasetype; parameters
Database type specifies the type of database. This parameter can beexcluded for Microsoft Jet Databases.
Database Property
This property returns a reference to a database connected through a datacontrol.
Syntax :
Object.Database
The Database object created by the Data control is based on the controlsDatabase Name, Exclusive Read Only and Connect properties. Databaseobjects have properties and methods you can use to manage your data. Youcan use any method of a Database object with the Database property of aData control such as close and execute. You can also examine the intervalstructure of database by using its TableDefs collection and in turn, the Fields,Indexes Collections of individual TableDef Objects.
DatabaseName Property
The DatabaseName Property reads or sets the name and location of thedatabase. Setting the value in the data controls Database Name Propertywhile your program is running, changes the database to which the control isconnected. You must use the Refresh method to reopen the control afterchanging databases for a data control.
Syntax :
-
7/28/2019 Vb Solved Qusetion Bank
37/46
DataControlName.DatabaseName = PathName
The following example closes a database referred by DBName variable afterconfirming from the user.
Private Sub OpenDatabaseNew (DBName as String)
ans = Msgbox(Close + Data1.DatabaseName+Now,VBYesNo,Confirm)
If ans = VBYes Then Data1.DatabaseName = DBName
Data1.Refresh
End If
End Sub
Exclusive Property
The Exclusive property reads or sets whether a database is opened for single
user or multiuser access. The data control exclusively reads or writes thedatabase at both design time and runtime, if set to True.
Syntax :
Object.Exclusive = True False
ReadOnly Property
ReadOnly property returns or sets a value that determines whether thecontrols Database is opened for read-only access.
Syntax :
Object.ReadOnly [ =boolean]The object expression evaluates to a data object and a Boolean expressiondetermines read/write access.
The controls Database object is opened with read-only access when set toTrue. Changes to data arent allowed. The controls Database is opened withread/write access to when set False.
You can use the ReadOnly property with a Data control to specify whetherdata in the underlying Database can be changed. For example, you mightcreate an application that only displays data. Accessing a Database usingread-only results in faster access.
For a Data control, this property is used only the first time a database isopened by your application. If your application subsequently opens otherinstances of the database, the property is ignored. For a change in thisproperty to take effect, you must close all instances of the databases andthen use the Refresh method.
Recordset Property
-
7/28/2019 Vb Solved Qusetion Bank
38/46
The Recordset property sets or returns a Recordset object defined by a Datacontrols properties or by an existing Recordset object.
You can use the Recordset property like any other Recordset object. Forexample, you can use any of the Recordset methods or properties to examinethe structure of the Recordset objects underlying schema.
You can also request the type of Recordset to be created by setting the Datacontrols Recordset Type property. If you dont request a specific type, adynaset-type Recordset is created. Using the RecordsetType property, youcan request to create either a Table -, Snapshot or dynaset typeRecordset.
The syntax for the Recordset property is as follows :
Set Object.RecordSet = value
Object refers to a valid Data control name and value is any object variablecontaining a reference to a RecordSet object.
RecordSource Property
The RecordSource Property specifies the source of the records accessiblethrough bound controls on your Form.
Syntax :
Object.RecordSource = [SQL Query Table Name ProcedureName]
The object expression evaluates to a Data control. Values can be the nameof any table in the database specified by the DatabaseName property of the
Data control or any table defined in the database objects TableDefscollection. Value can be also a string variable or a string containing aSQL.query. It can also be the name of any stored procedure in the Database.
If you set the RecordSource property to the name of an existing table in thedatabase, all of the fields in that table are visible to the bound controlsattached to the Data control. For table-type recordsets (RecordsetType =vbRSTypeTable), the order of the records retrieved is set by the Index objectthat you select using the Index property of the Recordset. For dynaset-typeand snapshot-type Recordset objects, you can order the records by using anSQL statement with an Order By clause in the RecordSource property of theData control. Otherwise, the data is returned in no particular order.
If you set the RecordSource property to the name of an existing QueryDef inthe database, all fields returned by the QueryDef are visible to the boundcontrols attached to the Data control. The order of the records retrieved isset by the QueryDef objects query. For example, the QueryDef may includean ORDER BY clause to change the order of the records returned by theRecordset created by the Data control or a WHERE clause to filter therecords.
-
7/28/2019 Vb Solved Qusetion Bank
39/46
You must use the Refresh method on a Data control to reopen the database ifthe RecordSource, property settings have changed and rebuild the dynaset inthe controls Recordset property.
Example 1
Data1.RecordSource = Select * from Emp where EMPID >=1001
Data1.Refresh
The Refresh Method
The refresh method when applied to a data control, opens or reopens adatabase specified in the DatabaseName property of Data control.
Syntax :
Object.Refresh
This refresh method also resets the current record back to the first record or(row) in the table.
Important Events Of The Data Control
Error Event
This event occurs only as the result of a data access error that takes placewhen no Visual Basic code is being executed. The general form of this eventprocedure is
Private Sub object_Error([Index As Integer,] dataerr As Integer,
response As Integer)End Sub
Index identifies the control if its in a control array, contains the indexnumber of the Data control. Dataerr returns the error number and responseis a number corresponding to the response you want to take, as describedbelow :
Constant Value Description
DataErrContinue 0 Ignores the error and continues theexecution of the program.
VbDataErrDisplay 1 Displays the Error message. This is bydefault.
Run-time errors can occur when none of your code is running, as when :
A user clicks a Data control button.
The Data control automatically opens a database and loads a Recordsetobject after the Form_Load event.
-
7/28/2019 Vb Solved Qusetion Bank
40/46
A custom control performs an operation such as the MoveNext method,and AddNew method or the Delete method.
If an error results from one of these actions, the Error event occurs.
If an event procedure has not been written for the Error event, Visual Basicitself displays the message associated with the error.
Reposition Event
Reposition event occurs after a record becomes the current record. When aData control is loaded, the first record in the Recordset object becomes thecurrent record. Whenever a user clicks any button on the Data control,moving from record to record, or if you use one of the Move methods, such asMoveNext, the Find methods, such as FindFirst, or any other property ormethod that changes the current record, the Reposition event occurs after,when each record becomes current. Delete, Unload, Update are few actionscausing this event. The general form of this event is :
Private Sub Object.Reposition([Index As Integer])
End Sub
Index specifies the index number of control if it is a part of control array. Incontrast, the Validate event occurs before moving to a different record.Youcan use this event to perform calculations based on data in the currentrecord.
Validate Event
The Validate event occurs before the reposition event (or a different record
becomes the current record). Validate event procedure has two argumentsIndex number as integer for the Data control, if it is a part of a Data controlarray, Save a Boolean expresssion specifying whether bound Data haschanged or not and Action an integer specifying operation that causes thisevent. Values for action are :
Constant Value Description
VbDataActionCancel 0 Cancels the operation when the sub exits.
VbDataActionMoveNext 3 Caused due to MoveNext method.
VbDataActionMoveLast 4 Caused due to MoveLast method.
VbDataActionAddNew 5 Caused due to AddNew method.
VbDataActionUpdate 6 Caused due to Update method.
VbDataActionDelete 7 Caused due to Delete method.
VbDataActionFind 8 Caused due to Find method.
VbDataActionUnload 11 Caused due to Form being unloaded.
-
7/28/2019 Vb Solved Qusetion Bank
41/46
This event occurs even if no changes have been made to data in the boundcontrols and even if no bound controls exist. You can use this event tochange values and update data. You can also choose to save data to stopwhatever action is causing the event to occur and substitute a differentaction.
You can change the action argument to convert one action into another. Youcan change the various Move methods and the Addnew method, which canbe freely exchanged. Any action can be stopped by setting action to 0.
You can check the data in each bound control where DataChanged is True.You can then set DataChanged to False to avoid saving that data in thedatabase. If it is invalid or corrupted, you can't use any methods such asMoveNext on the underlying Recordset object during this event.
Using Objects
Visual Basic allows you to create objects to represent a database, Recordsets,Fields etc. This makes the job easier in programming a Database application.
You can then easilty manipulate the objects or change the DataSourceaccording to your requirement in run-time.
Data Access Object (DAO) has been the simple Database access methods forVisual Basic programmers. You can use the Database and RecordSet objects.
The RecordSet and Database objects, each has properties and methods oftheir own. You can either use a Database, RecordSet object created by a Datacontrol or create an instance of you own, to manipulate the data.
Database Object
A Database object represents a Database. A Database object contains
Recordsets, QueryDefs, and Procedures. A Database object is declared withina Workspace object, which is a part of Workspace collection.
A database object can be declared using the following code :
Dim MyDb As Database
Dim MyWrk As WorkSpace
Set MyWrk = WorkSpaces(0)
Set MyDB = MyWrk. OpenDatabase
("C:\ProgramFiles\MicrosoftOffice\Office\Samples\_ Northwind.MDB)
The OpenDatabase method of the Workspace object opens a database andreturns its reference to a valid Database type object variable.
Important Methods Of A Database Object Are
Close Closes an open Database Access Object.
Execute Runs an Action Query or executes an SQL statement.
-
7/28/2019 Vb Solved Qusetion Bank
42/46
ExecuteSQL Executes an Action Query as an SQL statement on anODBC database.
OpenRecordset Creates a new Recordset object and applies it to theRecordset collection.
Refresh Refresh method closes or rebuilds the Recordset object.
Important Properties Of the Database Object
Connect Specifies the source of an open database. The default sourcefor ODBC and certain
ISAM drivers in Jet databases.
Count Returns the number of objects in a collection.
Name Returns or sets a user defined name for data access objects.
Recordset Object
A Recordset object represents the entire set of records from a base table orthe set of records resulted by an executed query. At any time, Recordsetobject refers only to a single record within the set as the current record.
A RecordSet object can be used to manipulate, and access the data. In orderto navigate records in the Database you can use various methods of theRecordSet object.
The number of records returned by the Recordset can be determined bymoving to the last record in the Recordset or by examining the Recordsetobjects RecordCount property. Before you move to the last record, the valuereturned by the property to display the number of records in a Data controls
Recordset :
Data1.Recordset.MoveLast
MsgBox Records & Data1.Recordset.RecordCount
If you create a Recordset object using either code for another Data Control,you can set the Recordset property of the Data control to this new Recordset.Any existing Recordset in the Data control, and the Database objectassociated with it are released when a new Recordset is assigned to theRecordset property.
The five types of RecordSet objects are :
Table type Recordset
Dynaset type Recordset
Snapshot type Recordset
Forward only type RecordSet
Dynamic type RecordSet
-
7/28/2019 Vb Solved Qusetion Bank
43/46
All the above mentioned RecordSet objects represent a set of records. Let usdiscuss these different types of RecordSets.
Table Type RecordSet Object
The first type of RecordSet object is the Table-type RecordSet. A table typeobject can be created from a table in a Microsoft Access database, but notfrom an Open Database Connectivity (ODBC) or a linked table. When youcreate a table-type the Jet database engine opens the actual table and yoursubsequent data manipulations operate directly on base-table data. A table-type can be opened on only one table; it cannot be opened on a union queryor a select query with a join.
The best part of this type of object is that you can use index created for theunderlying table. This allows much faster sorting and searching than theother types.
DynaSet Type RecordSet Object
Dynaset-type Recordset object represents a result of a query that can haveupdatable records. A dynaset-type object can be created from either a localor a linked table, or with a row-returning query that joins tables. Its actuallya set of references to records in one or more tables. With a dynaset you canextract and update data from more than one table, including linked tablesfrom other databases. Heterogeneous updatable joints are a unique featureof dynaset-they enable you to use updatable queries against tables indifferent types of databases. You can use the Seek methods rather than Findmethods for a Dynaset-type Recordset object for better performance.
SnapShot Type Recordset Object
A Snapshot-type object is a static copy of a set of records as it exists at thetime the snapshot is created. A snapshot-type object can contain fields fromone or more tables in a database. You cant update a snapshot.
The main advantage of a snapshot is that it creates less processingoverheads than the other types, so it can run queries and return data faster,especially when working with ODBC data sources.
Forward Only
A Forward-only type object is identical to a SnapShot type object. A forward-only-type object, sometimes referred to as a forward-scrolling snapshot or aforward-only snapshot, provides a subset of the capabilities of a snapshot.With forward-only snapshots, you can move only in a forward directionthourgh the records. Objects of this type cannot be cloned and only support
-
7/28/2019 Vb Solved Qusetion Bank
44/46
the Move and MoveNext methods. Like snapshots, you cant update aforward-only-type object.
Dynamic Type Recordset Object
Dynamic type RecordSet object is a result of query from one or more basetables. You can add, change or delete records from a row-returning query.Besides this, records other users add, delete or edit in the base table are alsopresent in the RecordSet.
Although you can work with any of the above RecordSet object, you mustalways choose the correct RecordSet type, that suits or satisfies your desires.For example, you would like to work with the sorted data or a data wheresearching operations like FindFirst, Seek could be performed in a short spanof time, then you will go for indexed table type Recordset. Similarly, in orderto scan all the records you must use a Forward only type Recordset for betterperformance.
You can use the type argument of the Recordset object to choose theRecordSet type.
Important Methods of the RecordSet Object
AddNew
The Ms Access engine maintains a copy buffer where it keeps the pendingdata that it will be writing to the database.
The addnew method clears the copy buffer and moves the current record tothe end. This is like adding a new row.
Syntax:
Datacontrolname.Recordset.AddNew
TheAddnew method does not actually add the information to the database.This is done by the UPDATE method.
Update
This method sends the contents of the copy buffer to the table or dynaset.Syntax :
Datacontrolname.Recordset.Update
Example 2
Data1.Recordset.Addnew
-
7/28/2019 Vb Solved Qusetion Bank
45/46
Data1.Recordset.Fields(Author) = Homes
Data1.Recordset.Fields(Titles) = Iliad
Data1.Recordset.Update
This code adds a record to a table which has two fieldsAuthors and Title.
Update Controls
This method can be used to retain the original data in the bound controls andignore the changes made to the data by a user.
For e.g., this method can be used in the Cancel button to reset the contentsof bound controls to their original value.
Edit
This method copies the current record into the copy buffer for editing.
Example :
Data1.Recordset.Edit
Authorname = Data1.Recordset.Fields(Author)
Call Changefield(Authorname)
Data1.Recordset.Fields(Author) = Authorname
Data1.Recordset.Update
This code uses a user defined procedure called Changefield, which changes
the value of the field.
Delete
This method deletes the current record in the recordset.
Syntax :
Datacontrolname.Recordset.Delete
After delete you must move the record pointer away from the deleted recordby a move method.
Example 3
Data1.Recordset.Delete
Data1.Recordset.Moveprevious
Close
-
7/28/2019 Vb Solved Qusetion Bank
46/46
To close an open database attached to a data control or to close the specificrecordset currently attached to the control, use the following :
Syntax :
ObjectName.Close
ObjectName can be an open database, recordset, dynaset, snapshot ora table object.
You must use the update method before you close the database to save allthe pending changes made to the database.
UpdateRecord Method
Saves the current values of bound controls. Doesnt support namedarguments.
Syntax :
Object.UpdateRecord
The Object represents a RecordSet object.
Q19. what is form in VB ? what are the options available for creating Forms ? What are
the different parts of Form and parts of MDI form.How Simple form , multiple form and array of forms are handled? Explain with
examples.
Q20. discuss the following basic Active-X controls in VB with suitable examples:(a) List box Control
(b) Combo Box control(c) Scroll Bar Control(d) Image control.
Q21 Explain the following constructs with exaple
(a) SELECT CASE
(b) DO/LOOP WHILE
(c) EXIT FOR
Q22. Explain the following string handling function in VB with Examples
MID&, StrReverse,Replace,LCase and Val
Q23. Explain how can you create,read and write sequential files in VB
Ans: see question bank