Sunteți pe pagina 1din 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 workbench on which you make your programs in Visual Basic.

The Visual Basic IDE is a collection of menus, toolbars, and windows that make up your programming 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 menu bar'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 and set 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 menu bar. 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 a specific 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.

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 then invoke 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 toolbar offers 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 selecting controls from the ToolBox and placing them on your forms. Some controls are built into Visual Basic and can't be removed from the ToolBox; these controls 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

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 the tree, 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 clicking it 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 Basic programming, a good portion of your time will be spent learning, setting, and manipulating control properties. Because controls are the building blocks of Visual Basic programs, 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

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 Form Layout 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. To position 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 multiple windows 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 are declared and assigned values. Unlike variables, the values they hold remain unchanged

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=rock Const arr_counter as integer=30 Visual Basic provides many built-in constants that are useful with various statements. To See 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 considered for 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 Data Types 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

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 and it should be used when a great degree of precision is required. Currency The Currency data type is an 8 byte number with fixed decimal point. 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 a single 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 string variable 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 <variable name> As String * <nlength> Where <variablename> is the name given to the variable <nlength> is the maximum number of characters that the variable can hold.

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 = DAVIM Text1.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

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 CommandBotton Set x = Command1 Set y = Command2 x.Caption = OK y.Caption = Cancel End Sub

Variant Visual 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 of other 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 can accommodate all other data types. For Example: X = Welcome The 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:

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

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 then Exit For End if P=i*t Print 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 = 10 End 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

With Text1 .Text = "" .BackColor = &H8000000A .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 0 Text1.Text = "Bonjour" Case 1 Text1.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 Select End Sub Private Sub Command1_Click() End End Sub

'Gray

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 as the 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 look like 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 member variables 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 of Visual Basic object oriented programming. Begin by starting Visual Studio and creating a new Windows Application named vbObjects. Once the project opens, select the Project... menu and select Add class.... In the Add New Item dialog, name the new class file clsBankAccount.vb and click on the Add button.

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. Members can be Public or Private. 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 be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). 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 methods to access these values later, so will mark them as Private: Public Class clsBankAccount Private strAccountNumber As String Private strAccountName As String Private intBalance As Integer Private 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 is achieved using Get and Set methods. The syntax for get and Set methods is as follows: Public Property propertyName() As datatype Get .... Code to return property value End Get

Set(ByVal value As datatype ) .... 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 the Public Property line of the declaration, 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 String Private intBalance As Integer Private accountFee As Integer = 5 Public Property AccountName() As String Get End Get Set(ByVal value As String) End Set End Property Public Property Balance() As Integer Get Return intBalance End Get Set(ByVal value As Integer) intBalance = value End Set End Property End 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 Integer intBalance = 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.

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 class using 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 this approach 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 be slowed 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 and execution speed is increased because the binding takes place at compile time - not at runtime. 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 that we created Get and Set functions the data members of our class. Because we did this, we

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 the account 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 are sure 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 tracing what 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.

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 to the 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 the active 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 break mode: 1) 2) Breakpoint Stop Statement

Break Mode can be entered manually in several ways: 1) 2) 3) You press CTRL+BREAK Select the Break button on the toolbar Press F5 while your program is running

Setting Breakpoints A breakpoint works as marker in the code that tells Visual Basic to suspend program execution. 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 the project , 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

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 Integer For 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 program executes. Adding a watch expression 1. 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" Next Print Print "loop is ended" End Sub

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 test procedures, evaluate expressions , or assign new values to variables or properties in the code. 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 or properties out of scope are not displayed

Debug.Print statement

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), vbRed Picture1.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) (ii) (iii) Database support in VB Recursion 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 also share 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 proiperty setting and control arrays are used in menu control and option but on groupings.

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 become the first element in the array.

4. Set the text boxs properties as follows: Name Property to txtArr Text Property clear Text1 Index property to no value

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 any other group of related information. Let us consider the following situation:

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 out the 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 simple solution 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 is the 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) = Rohit Player(1) = Anil . Player(10) = Rajiv The keyword AS can be used optionally to specify the type of the arrays elements.

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 5 marks(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. Some subroutines 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 code to 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 eliminate redundancy. Consider a complicated program like a word processor. When certain

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 be prompted 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 places in 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 every place 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 would only 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 code editor 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 be covered later in the lesson.
Sub TestSub() End Sub

After you enter the first line and press Enter, the second line will automatically be added for 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

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 file from 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 your subroutine 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 error rather 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

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 the parenthesis. 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 parameters 5 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:
Private Sub DisplayAdd(x As Integer, y As Integer) MsgBox x + y End Sub Private Sub Form_Load() Dim a As Integer Dim b As Integer a = 5 b = 2 DisplayAdd a, b End Sub

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 b from 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 result in 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 doing this, the variables can be changed, but their values will not change outside of the called subroutine. 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.

Private Sub Swap(ByRef x As Integer, ByRef y As Integer) Dim temp As Integer temp = x x = y y = temp End Sub

Private Sub DisplayVals(ByRef a As Integer, ByVal b As Integer) 'Don't worry about understanding the next line yet, it will be explained later MsgBox "a = " & CStr(a) & vbCrLf & "b = " & CStr(b) End Sub Private Sub Form_Load() Dim a As Integer Dim b As Integer a = 10 b = 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, b End 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 the default. 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 a type, 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 integer Res = x + y
Add = Res End Function

Private Sub Form_Load() Dim a As Intege

Dim b As Integer Dim c As Integer a = 32 b = 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) DLL Ans: 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 modes and 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 ? write all steps. Ans: see also in question Bank

Database Management

A database can be viewed as a set of interrelated data. Database management deals with the storage, retrieval and editing of the data within the database. One of the most important functions of Database management is 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, utilizing database functionality that already exists becomes necessary. Visual Basic 6.0 provides full-fledged database engine called Jet. This engine contains virtually all the database functions that applications may need. The simplest and easiest way to access the Jet database engine is through bound data control. Data Access Object (DAO) has been the standard database access method for Visual Basic programmers. DAO was the first database interface included with Visual Basic in its third version. Remote Data Object (RDO) was then introduced to make data-access more flexible 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 take over all the other methods of data access.

Data Access Object


Data Access Object enables you to use a programming language to access and manipulate data in local or remote databases and to manage databases, their objects and their structure. DAO utilizes Microsofts Jet database engine and 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 a separate 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 object or creating a new one. The individual fields in a table make up a Recordsets Field object and table of a database is held in a Recordset Object. Data Access object is implemented through an ActiveX control called the Data Control. This allows a large amount of DAOs power to be utilized without having to add a single line of code. When used in conjunction with Data aware controls such as TextBox, DBList, DbCombo, DbGrid etc, the Data control becomes very powerful. Information from a database table is fetched by the DAO and then supplied to various 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, ODBC databases, 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

DBEngine consists of several Dynamic Link Libraries that are linked to your Visual Basic program at runtime. DBEngine is controlled by our application through 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 are called Data Bound controls and are simpler to use e.g., TextBox, Label DBGrid, DBList etc. These controls have basically two standard properties other than their regular properties. The DataSource property enables you to specify the name of the Data Control to which the client control will bind. The name of the Data Control(s) available on your form is already present in the dropped down Combo Box of this property in the property window. The Datafield property, a string property of the Client Control, specifies which of the Database field names available from the data control the client will bind. After the DataSource and Datafield properties are set, the Data Control is properly initialized, the Client Control automatically displays the contents of the 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, to change the Data contained in the Bound field. DBCombo and DBlist enable you to use the data control to provide a list of valid choices for a field, as well as 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. Data Control is one of them. Data Control was the first medium to connect the applications to a database in the third version of Visual Basic. The Data control is an excellent tool for rapidly developing a database information retrieval system. With very little code you can get a useful view into stored information. This is practically a drop-in-place process where by you can place a data control, A DBGrid and a Command Button on a form and be able to access your database in a matter of minutes. After you set properties your application is set to go.

Data Control
Data Control is one of the easiest modes to access databases. You can perform most data access operations using the Data control without writing any code at all. Data-aware controls bound to a Data control automatically display 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 control performs all operations on the current record.

If the Data control is instructed to move to a different record, all bound controls automatically pass any changes to the Data control to be saved in the database. The Data control then moves to the requested record and passes back data from the current record to the bound controls when its displayed. The Data control is itself smart enough to handle a number of contingencies including empty recordsets, adding new records, editing and updating existing records, and handling some types of errors. However, in more sophisticated applications, you need to trap some error conditions that the Data control cant handle. For example, if the Microsoft Jet database engine has a problem accessing the database file, doesnt have permission, or cant execute the query as coded, a trappable error results. If the error occurs before your application procedures start or due to some internal errors, the Errors event is triggered.

Data Control in Action

Using the data control


The data control is an intrinsic control used to bind that is, create a connection- between a database and control such as text boxes. A database is sent to data control via its properties. Then individual control is bound to data control.

To add a data control to a form:


1. With a form open, double-click the data control in the toolbox ( Figure 9.1). The data control is placed on the form ( Figure 9.2).

Figure 9.1

Figure 9.2

2.

Using the properties window, change the caption of the data control to something descriptive, such as click here to control data display ( Figure 9.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 data base 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)

Figure 9.5

3. 4.

From your file system, select the database. 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 in your visual basic home directory. Data control properties assignments can also be made in code. Biblio consists of publisher, author, and book table. Nwind is an inventory database of fictional food- trading company End of File and Beginning of File Actions The Data control can also manage what happens when you encounter a Recordset with no records. By changing the EOFAction property, you can program the Data control to enter Addnew mode automatically. These properties have been discussed later. Alignment You can program the Data control to automatically snap to the top or bottom of its parent form by using the Align property. In either case, the Data control is resized horizontally to fill the width of its parent form whenever the

parent form is resized. This property allows a Data control to be placed to an MDI 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 controls are 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 their regular properties. The DataSource property enables you to specify the name of the Data Control to which the client control will bind. The name of the Data Control(s) available on your form is already present in the drop down Combo Box of this property in the property window. The Datafield property, a string property of the Client Control, specifies which of the Database field names available from the data control, the client will bind. After the DataSource and Datafield properties are set, the Data Control is properly initialized, the Client Control automatically displays the contents of the 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 change the data contained in the bound field. DBCombo and DBList enables you to use the data control to provide a list of valid choices for a field, as well as to bind 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 a value indicating what action the data control takes when the BOF or EOF is encountered by Data control. Syntax: DataControlName.Recordset.BOFAction = value DataControlName.Recordset.EOFAction = value Different settings for the properties are : Constant VbBOFActionMoveFirst valid record. VbBOFActionBOF record, repositions Value 0 1 Description Moves the record pointer back to the first Causes a validation event on the first to the first record. Above given values are for the BOFAction property, values for EOFAction property are :

Constant VbEOFActionMoveLast record. VbEOFActionEOF record, repositions VbEOFActionAddNew an AddNew

Value 0 1 2

Description Moves the record pointer back to the last Causes a validation event on the last to the last record. After moving past the last record, triggers event after Validation event.

Connect Property
The Connect property sets or returns a value that provides information about the source of an open connection, an open database, a database used in a pass through query, or a linked table. This property is read/write for database 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 be excluded for Microsoft Jet Databases.

Database Property
This property returns a reference to a database connected through a data control. Syntax : Object.Database The Database object created by the Data control is based on the controls Database Name, Exclusive Read Only and Connect properties. Database objects have properties and methods you can use to manage your data. You can use any method of a Database object with the Database property of a Data control such as close and execute. You can also examine the interval structure 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 the database. Setting the value in the data controls Database Name Property while your program is running, changes the database to which the control is connected. You must use the Refresh method to reopen the control after changing databases for a data control. Syntax :

DataControlName.DatabaseName = PathName The following example closes a database referred by DBName variable after confirming from the user. Private Sub OpenDatabaseNew (DBName as String) ans = VBYesNo,Confirm) Msgbox(Close + Data1.DatabaseName+Now,

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 the database 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 the controls Database is opened for read-only access. Syntax : Object.ReadOnly [ =boolean] The object expression evaluates to a data object and a Boolean expression determines read/write access. The controls Database object is opened with read-only access when set to True. Changes to data arent allowed. The controls Database is opened with read/write access to when set False. You can use the ReadOnly property with a Data control to specify whether data in the underlying Database can be changed. For example, you might create an application that only displays data. Accessing a Database using read-only results in faster access. For a Data control, this property is used only the first time a database is opened by your application. If your application subsequently opens other instances of the database, the property is ignored. For a change in this property to take effect, you must close all instances of the databases and then use the Refresh method.

Recordset Property

The Recordset property sets or returns a Recordset object defined by a Data controls properties or by an existing Recordset object. You can use the Recordset property like any other Recordset object. For example, you can use any of the Recordset methods or properties to examine the structure of the Recordset objects underlying schema. You can also request the type of Recordset to be created by setting the Data controls Recordset Type property. If you dont request a specific type, a dynaset-type Recordset is created. Using the RecordsetType property, you can request to create either a Table -, Snapshot or dynaset type Recordset. 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 variable containing a reference to a RecordSet object.

RecordSource Property
The RecordSource Property specifies the source of the records accessible through bound controls on your Form. Syntax : Object.RecordSource = [SQL Query Table Name Procedure Name] The object expression evaluates to a Data control. Values can be the name of any table in the database specified by the DatabaseName property of the Data control or any table defined in the database objects TableDefs collection. Value can be also a string variable or a string containing a SQL.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 the database, all of the fields in that table are visible to the bound controls attached to the Data control. For table-type recordsets (RecordsetType = vbRSTypeTable), the order of the records retrieved is set by the Index object that you select using the Index property of the Recordset. For dynaset-type and snapshot-type Recordset objects, you can order the records by using an SQL statement with an Order By clause in the RecordSource property of the Data control. Otherwise, the data is returned in no particular order. If you set the RecordSource property to the name of an existing QueryDef in the database, all fields returned by the QueryDef are visible to the bound controls attached to the Data control. The order of the records retrieved is set by the QueryDef objects query. For example, the QueryDef may include an ORDER BY clause to change the order of the records returned by the Recordset created by the Data control or a WHERE clause to filter the records.

You must use the Refresh method on a Data control to reopen the database if the RecordSource, property settings have changed and rebuild the dynaset in the 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 a database 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 place when no Visual Basic code is being executed. The general form of this event procedure 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 index number of the Data control. Dataerr returns the error number and response is a number corresponding to the response you want to take, as described below : Constant DataErrContinue execution of the Value 0 Description Ignores the error and continues program. the

VbDataErrDisplay 1 default.

Displays the Error message.

This is by

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 Recordset object after the Form_Load event.

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 Basic itself displays the message associated with the error.

Reposition Event
Reposition event occurs after a record becomes the current record. When a Data control is loaded, the first record in the Recordset object becomes the current 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 as MoveNext, the Find methods, such as FindFirst, or any other property or method that changes the current record, the Reposition event occurs after, when each record becomes current. Delete, Unload, Update are few actions causing 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. In contrast, the Validate event occurs before moving to a different record.You can use this event to perform calculations based on data in the current record.

Validate Event
The Validate event occurs before the reposition event (or a different record becomes the current record). Validate event procedure has two arguments Index number as integer for the Data control, if it is a part of a Data control array, Save a Boolean expresssion specifying whether bound Data has changed or not and Action an integer specifying operation that causes this event. Values for action are : Constant VbDataActionCancel VbDataActionMoveNext VbDataActionMoveLast VbDataActionAddNew VbDataActionUpdate VbDataActionDelete VbDataActionFind VbDataActionUnload 8 Value 0 3 4 Description Cancels the operation when the sub exits. Caused due to MoveNext method. Caused due to MoveLast method. 5 6 7 Caused due to AddNew method. Caused due to Update method. Caused due to Delete method.

Caused due to Find method. 11 Caused due to Form being unloaded.

This event occurs even if no changes have been made to data in the bound controls and even if no bound controls exist. You can use this event to change values and update data. You can also choose to save data to stop whatever action is causing the event to occur and substitute a different action. You can change the action argument to convert one action into another. You can change the various Move methods and the Addnew method, which can be 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 the database. If it is invalid or corrupted, you can't use any methods such as MoveNext 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 DataSource according to your requirement in run-time. Data Access Object (DAO) has been the simple Database access methods for Visual Basic programmers. You can use the Database and RecordSet objects. The RecordSet and Database objects, each has properties and methods of their own. You can either use a Database, RecordSet object created by a Data control 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 within a 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 and returns its reference to a valid Database type object variable.

Important Methods Of A Database Object Are


Close Execute Closes an open Database Access Object. Runs an Action Query or executes an SQL statement.

ExecuteSQL ODBC database.

Executes an Action Query as an SQL statement on an

OpenRecordset Creates a new Recordset object and applies it to the Recordset 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 source for ODBC and certain ISAM drivers in Jet databases. Count Name Returns the number of objects in a collection. 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 or the set of records resulted by an executed query. At any time, Recordset object 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 order to navigate records in the Database you can use various methods of the RecordSet object. The number of records returned by the Recordset can be determined by moving to the last record in the Recordset or by examining the Recordset objects RecordCount property. Before you move to the last record, the value returned 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 object associated with it are released when a new Recordset is assigned to the Recordset property. The five types of RecordSet objects are :

Table type Recordset Dynaset type Recordset Snapshot type Recordset Forward only type RecordSet Dynamic type RecordSet

All the above mentioned RecordSet objects represent a set of records. Let us discuss these different types of RecordSets.

Table Type RecordSet Object


The first type of RecordSet object is the Table-type RecordSet. A table type object can be created from a table in a Microsoft Access database, but not from an Open Database Connectivity (ODBC) or a linked table. When you create a table-type the Jet database engine opens the actual table and your subsequent data manipulations operate directly on base-table data. A tabletype can be opened on only one table; it cannot be opened on a union query or a select query with a join. The best part of this type of object is that you can use index created for the underlying table. This allows much faster sorting and searching than the other types.

DynaSet Type RecordSet Object


Dynaset-type Recordset object represents a result of a query that can have updatable records. A dynaset-type object can be created from either a local or a linked table, or with a row-returning query that joins tables. Its actually a set of references to records in one or more tables. With a dynaset you can extract and update data from more than one table, including linked tables from other databases. Heterogeneous updatable joints are a unique feature of dynaset-they enable you to use updatable queries against tables in different types of databases. You can use the Seek methods rather than Find methods 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 the time the snapshot is created. A snapshot-type object can contain fields from one or more tables in a database. You cant update a snapshot. The main advantage of a snapshot is that it creates less processing overheads 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 forwardonly-type object, sometimes referred to as a forward-scrolling snapshot or a forward-only snapshot, provides a subset of the capabilities of a snapshot. With forward-only snapshots, you can move only in a forward direction thourgh the records. Objects of this type cannot be cloned and only support

the Move and MoveNext methods. forward-only-type object.

Like snapshots, you cant update a

Dynamic Type Recordset Object


Dynamic type RecordSet object is a result of query from one or more base tables. 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 also present in the RecordSet. Although you can work with any of the above RecordSet object, you must always 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 where searching operations like FindFirst, Seek could be performed in a short span of time, then you will go for indexed table type Recordset. Similarly, in order to scan all the records you must use a Forward only type Recordset for better performance. You can use the type argument of the Recordset object to choose the RecordSet type.

Important Methods of the RecordSet Object

AddNew
The Ms Access engine maintains a copy buffer where it keeps the pending data that it will be writing to the database. The addnew method clears the copy buffer and moves the current record to the end. This is like adding a new row. Syntax: Datacontrolname.Recordset.AddNew The Addnew 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

Data1.Recordset.Fields(Author) = Homes Data1.Recordset.Fields(Titles) = Iliad Data1.Recordset.Update This code adds a record to a table which has two fields Authors and Title.

Update Controls
This method can be used to retain the original data in the bound controls and ignore the changes made to the data by a user. For e.g., this method can be used in the Cancel button to reset the contents of 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 record by a move method.

Example 3
Data1.Recordset.Delete Data1.Recordset.Moveprevious

Close

To close an open database attached to a data control or to close the specific recordset currently attached to the control, use the following : Syntax : ObjectName.Close ObjectName can be an open database, recordset, dynaset, snapshot or a table object. You must use the update method before you close the database to save all the pending changes made to the database.

UpdateRecord Method
Saves the current values of bound controls. arguments. Syntax : Object.UpdateRecord The Object represents a RecordSet object. Doesnt support named

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

S-ar putea să vă placă și