Visual Basic Programming Aan

download Visual Basic Programming Aan

of 112

Transcript of Visual Basic Programming Aan

  • 8/12/2019 Visual Basic Programming Aan

    1/112

    VISUAL BASIC

    1

    VISUAL BASIC

    1. INTRODUCTION TO VISUAL BASIC................................................................ 31.1 What is Visual Basic? ........... ............. ............. ............. ............. ............. ............. ................. ..... 31.2 Working With Visual Basic.............. ............. ............. ............. ............. ............. ............. ........... 51.3 Starting Visual Basic............... ............. ............. ............. ............. ............. ............. ................. ... 5

    1.4 Designing an Effective USER interface ............ ............. ............. ............. ............. ............ ......... 91.5 Defining properties ............. ............. ............. ............. ............. ............. ............. ................ ...... 10

    2. PROGARMMING IN VB ....................................................................................142.1 General Terms used in VB ............. ............. ............. ............. ............. ............. ............. ........... 142.2 Variables ................................................................................................................................ 152.3 Programming Fundamentals....... ............. ............. ............. ............. ............. ............. ............. .. 152.4 Working with Procedures............ ............. ............. ............. ............. ............. ............. .............. 172.5 Setting and Retrieving Properties ............ ............. ............. ............. ............. ............. ............... 202.6 Controls on Other Forms........... ............. ............. ............. ............. ............. ............. ............... . 21

    3. INTRODUCTION TO BOUND CONTROLS......................................................233.1 Introduction ............................................................................................................................ 233.2 Data Control ........................................................................................................................... 23

    3.3 TYPES OF CONTROL........... ............. ............. ............. ............. ............. ............ ............. ...... 23

    4. DATABASE CONNECTIONS ............................................................................314.1 Database................................................................................................................................. 314.2 Creating Recordsets ............. ............. ............. ............. ............. ............. ............. ............... ...... 324.3 Selecting Records ............ ............. ............. ............. ............. ............. ............. ............. ............ 344.4 Positioning the Current Record in a Recordset ............. ............. ............. ............. ............. ........ 344.5 Using Recordsets to Manipulate Data............ ............. ............. ............. ............. ............. ......... 364.6 Using QueryDef Variables ............ ............. ............. ............. ............. ............. ............. ............ 364.7 Data Control and Bound Controls....... ............. ............. ............. ............. ............ ............. ........ 374.8 Programming with the Data Control ............. ............. ............. ............. ............. ............. .......... 384.9 Using SQL.............. ............. ............. ............. ............. ............. ............. ............. ............... ...... 42

    5. QUERIES.............................................................................................................465.1 Select Queries....... ............. ............. ............. ............. ............. ............. ............. ................ ...... 465.2 Cross Tab Queries.................... ............. ............. ............. ............. ............. ............. ................ . 485.3 Action Queries........... ............. ............. ............. ............. ............. ............. ............. ................. . 485.4 SQL Queries.. ............. ............. ............. ............. ............. ............. ............. ............. ................ . 505.5 Relationships.......................................................................................................................... 515.6 Querying a Database............. ............. ............. ............. ............. ............. ............. ................. ... 52

    6. MENUS AND DIALOG BOXES.........................................................................546.1 Menus .................................................................................................................................... 546.2 Dialog boxes.............. ............. ............. ............. ............. ............. ............. ............. ............... ... 58

    7. VISUAL BASIC REPORT...................................................................................607.1 Definition ............................................................................................................................... 607.2 Using Crystal reports ............ ............. ............. ............. ............. ............. ............. ................. ... 607.3 VB code by using Printer object & Print form method. ............ ............. ............. ............. ....... 697.4 Sample Programs and reports............ ............. ............. ............. ............. ............. ............. ........ 79

    8. ADVANCED PROGRAMMING IN VISUAL BASIC.........................................828.1 Multiple Document Interface................ ............. ............. ............. ............. ............. ............. ..... 828.2 Object Linking/ Embedding (OLE) ............ ............. ............. ............. ............. ............. ............ 868.3 Active X Designers....... ............. ............. ............. ............. ............. ............. ............. ............... 898.4 Debugging and Error Handling........... ............. ............. ............. ............. ............. ............. ....... 92

    9. ADVANCED TOOLS IN VB...............................................................................989.1 Active X Control.......... ............. ............. ............. ............. ............. ............. ............. ................ 989.2 Using The MSCHART Control ............. ............. ............. ............. ............. ............. ............. .... 98

  • 8/12/2019 Visual Basic Programming Aan

    2/112

    VISUAL BASIC

    2

    9.3 Using The Multimedia MCI Control................... ............. ............. ............. ............. ............. .. 1029.4 Using Animation Control ............. ............. ............. ............. ............. ............. ............. ........... 1059.5 Using Status Bar Control.......... ............. ............. ............. ............. ............. ............. ............... 106

    10. VB EXERCISE ................................................................................................111

  • 8/12/2019 Visual Basic Programming Aan

    3/112

    VISUAL BASIC

    3

    1. INTRODUCTION TO VISUAL BASIC

    1.1 What is Visual Basic?

    Microsoft Visual Basic is the fastest and easiest way to create applications for Microsoft Windows.

    Whether you are an experienced professional or brand new to Windows programming, Visual Basicprovides you with a complete set of tools to simplify rapid application development.The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather thanwriting numerous lines of code to describe the appearance and location of interface elements, yousimply drag and drop prebuilt objects into place on screen. If you've ever used a drawing program suchas Paint, you already have most of the skills necessary to create an effective user interface.

    The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) language, alanguage used by more programmers than any other language in the history of computing. Visual Basichas evolved from the original BASIC language and now contains several hundred statements,functions, and keywords, many of which relate directly to the Windows GUI. Beginners can createuseful applications by learning just a few of the keywords, yet the power of the language allowsprofessionals to accomplish anything that can be accomplished using any other Windows programminglanguage.

    1.1.1 Visual Basic Versions

    Visual Basic is available in three versions, each geared to meet a specific set of developmentrequirements. The Visual Basic Learning edition allows programmers to easily create powerful applicationsfor Microsoft Windows 95 and Windows NT. It includes all intrinsic controls, plus grid, tab, anddata-bound controls. The Professional edition provides computer professionals with a full-featured set of tools fordeveloping solutions for others. It includes all the features of the Learning edition, plus additionalActiveX controls, including Internet controls, and the Crystal Report Writer.. The Enterprise edition allows professionals to create robust distributed applications in a teamsetting. It includes all the features of the Professional edition, plus the Automation Manager,

    Component Manager, database management tools, the Microsoft Visual SourceSafe project-orientedversion control system, and more.Before you install Visual Basic, make sure that your computer meets the minimum requirements, andread the Readme file, located at the root directory on your installation disk.

    1.1.2 Hardware and System Requirements

    To run Visual Basic, you must have certain hardware and software installed on your computer. Thesystem requirements include:

    Microsoft Windows NT 3.51 or later, or Microsoft Windows 95.

    80486 or higher microprocessor.

    A hard disk with a minimum of 50 megabytes available space for a full installation.

    A CD-ROM disc drive.

    VGA or higher-resolution screen supported by Microsoft Windows. 16 MB of RAM.

    A mouse or other suitable pointing device.

    1.1.3 Structure of a VB project

    The project file is simply a list of all the files and objects associated with the project, as well asinformation on the environment options you set. This information is updated every time you save theproject. All of the files and objects can be shared by other projects as well.

  • 8/12/2019 Visual Basic Programming Aan

    4/112

  • 8/12/2019 Visual Basic Programming Aan

    5/112

  • 8/12/2019 Visual Basic Programming Aan

    6/112

    VISUAL BASIC

    6

    Once you start the Visual Basic, the development environment includes a variety of overlappingwindows. At the top of the screen is the title bar.

    1.3.2 Creating the Interface

    Forms are the foundation for creating the interface of an application. You can use forms to addwindows and dialog boxes to your application. You can also use them as containers for items that arenot a visible part of the application's interface. For example, you might have a form in your applicationthat serves as a container for graphics that you plan to display in other forms.There are three main steps to creating an application in Visual Basic:

    1. Create the interface.

    2. Set properties.

    3. Write code.

    1.3.3 Menu Bar

    The menu bar is a a row of buttons that make up the toolbar. They are designed to give ways toperform specific operations. The position and size indicators are designed to help the user in arrangingthe objects of a project.The first step in building a Visual Basic application is to create the forms that will be the basis for yourapplication's interface. Then you draw the objects that make up the interface on the forms you create.For this first application, you'll use two controls from the Toolbox.

  • 8/12/2019 Visual Basic Programming Aan

    7/112

  • 8/12/2019 Visual Basic Programming Aan

    8/112

    VISUAL BASIC

    8

    DriveListBox

    A DriveListBox control enables a user to select a valid disk drive at run time. Use this control todisplay a list of all the valid drives in a user's system. You can create dialog boxes that enable theuser to open a file from a list of files on a disk in any available drive.

    FileListBox

    A FileListBox control locates and lists files in the directory specified by the Path property at run

    time. Use this control to display a list of files selected by file type. You can create dialog boxes inyour application that, for example, enable the user to select a file or group of files.

    Frame

    A Frame control provides an identifiable grouping for controls. You can also use a Frame tosubdivide a form functionallyfor example, to separate groups of OptionButton controls.

    Scroll bars

    Scroll bars provide easy navigation through a long list of items or a large amount of information.They can also provide an analog representation of current position. You can use a scroll bar as aninput device or indicator of speed or quantityfor example, to control the volume of a computergame or to view the time elapsed in a timed process.

    Image control

    Use the Image control to display a graphic. An Image control can display a graphic from a bitmap,icon, or metafile, as well as enhanced metafile, JPEG, or GIF files.

    Label control

    A Label control is a graphical control you can use to display text that a user can't change directly.

    Line control

    A Line control is a graphical control displayed as a horizontal, vertical, or diagonal line.

    ListBox

    A ListBox control displays a list of items from which the user can select one or more. If thenumber of items exceeds the number that can be displayed, a scroll bar is automatically added tothe ListBox control.

    If no item is selected, the ListIndex property value is -1. The first item in the list is ListIndex 0,and the value of the ListCount property is always one more than the largest ListIndex value.

    Menu control

    A Menu control displays a custom menu for your application. A menu can include commands,submenus, and separator bars. Each menu you create can have up to four levels of submenus.

    OptionButton control

    An OptionButton control displays an option that can be turned on or off.

    PictureBox control

    A PictureBox control can display a graphic from a bitmap, icon, or metafile, as well as enhancedmetafile, JPEG, or GIF files. It clips the graphic if the control isn't large enough to display theentire image

    Shape control

    The Shape control is a graphical control displayed as a rectangle, square, oval, circle, roundedrectangle, or rounded square.

    TextBox control

  • 8/12/2019 Visual Basic Programming Aan

    9/112

    VISUAL BASIC

    9

    A TextBox control, sometimes called an edit field or edit control, displays information entered atdesign time, entered by the user, or assigned to the control in code at run time.

    Timer control

    A Timer control can execute code at regular intervals by causing a Timer event to occur.

    1.3.5 Forms in a Project

    Placing Control on a formControls can be placed in a form by selecting controls from the tool box and by positioning it on theappropriate position in the form.Running a ProgramOnce a form is created, you can execute it even before writing the program by clicking the start buttonor by the Start command in the Run menu. This helps the user in exploring the behavior of the controlsplaced in the form.Properties WindowAfter the controls were placed in the required order, user can set the properties of these controls byselecting the Properties icon from the tool bar or by selecting the properties from the view menu.Properties determine the appearance and behavior of individual controls and forms in the applications.

    In the properties window, the column on the left contains the names of all the properties that applies toa selected object, and the right column shows the setting for each property.

    Project windowThe Project window provides a list of the files in the current program/application. Each programcontains one project window, which is sorted on disk with a default extension name of MAK/VBPdepending on the version of VB. To view the project window user can click on the Project icon in thetool bar or select from the menu. The forms in a project are saved as FRM files. There can be morethan one FRM files in a project. There will also be Module file (.BAS) and control files (VBX) in aProject file created in VB.

    Writing CodeThe event procedures for the controls on a particular form is saved as part of the FRM file (Form file)for writing the code, user an either double click on the controls in a form or view it in the Code view.

    1.4 Designing an Effective USER interfaceAn interface includes all the visual objects and procedural techniques that define a programsinteraction with the user. In the VB environment user can create programs interface by dragging thecontrols into a form and arranging them in place. The Tool Box provides an assortment of controls thatmeet particular requirements in a programs design. These controls are designed so that a user canlearn to operate them almost without any instruction.

    1.4.1 Adding Controls to the form

    The first step in creating the program window is to reposition and resize the form window itself to suitthe programs design. User may decrease or increase the dimensions of the form and appropriately

    centre it o the desktop. Once the form window is set to the required dimensions, user may add controlsto it by selecting from the tool box and dragging it to the form.

    1.4.2 Adjusting the form design grid

    Visual Basics standard form grid can be changed by setting the values of grid width, height etc., in theOptions/Environment menu. To make the grid visible select yes for Show Grid option.

  • 8/12/2019 Visual Basic Programming Aan

    10/112

    VISUAL BASIC

    10

    1.5 Defining properties

    All controls, command button, text box, label, option button has its own list of properties that applyspecifically to the objects design. The properties determine how the program behaves in run time, andits quality of interaction with the user. These properties include keyboard shortcut sequences forcommand button, order of items arranged in a list, focus in response to tab keys, a control is active orinactive, visible or not etc.. Some of the properties used by forms and controls are listed below:

    Appearance property Returns or sets the paint style of controls on an MDIForm or Form object at design time. Read-

    only at run time.

    BackColor, ForeColor Properties

    BackColor returns or sets the background color of an object.

    ForeColor returns or sets the foreground color used to display text and graphics in an object.

    Container Property

    Returns or sets the container of a control on a Form. Not available at design time.

    DataChanged Property

    Returns or sets a value indicating that the data in the bound control has been changed by someprocess other than that of retrieving data from the current record. Not available at design time.

    DataField Property

    Returns or sets a value that binds a control to a field in the current record

    DragIcon Property

    Returns or sets the icon to be displayed as the pointer in a drag-and-drop operation.

    DragMode Property

    Returns or sets a value that determines whether manual or automatic drag mode is used for a drag-and-drop operation.

    Enabled Property

    Returns or sets a value that determines whether a form or control can respond to user-generatedevents.

    Font Property

    Returns a Font object.

    FontBold, FontItalic, FontStrikethru, FontUnderline Properties

    Return or set font styles in the following formats: Bold, Italic, Strikethru, and Underline

    FontName Property

  • 8/12/2019 Visual Basic Programming Aan

    11/112

    VISUAL BASIC

    11

    Returns or sets the font used to display text in a control or in a run-time drawing or printingoperation.

    Note The FontName property is included for use with the CommonDialog control and forcompatibility with earlier versions of Visual Basic. For additional functionality, use the new Fontobject properties (not available for the CommonDialog control).

    FontSize Property

    Returns or sets the size of the font to be used for text displayed in a control or in a run-timedrawing or printing operation.

    Note The FontSize property is included for use with the CommonDialog control and forcompatibility with earlier versions of Visual Basic. For additional functionality, use the new Fontobject properties (not available for the CommonDialog control).

    Height, Width Properties

    Return or set the dimensions of an object or the width of the Columns object of a DBGrid control.For the Printer and Screen objects, not available at design time.

    HelpContextID Property

    Returns or sets an associated context number for an object. Used to provide context-sensitive Helpfor your application.

    hWnd Property

    Returns a handle to a form or control.

    Note This property is not supported for the OLE container control.

    Index Property (Control Array)

    Returns or sets the number that uniquely identifies a control in a control array. Available only ifthe control is part of a control array.

    IntegralHeight Property

    Returns or sets a value indicating if the control displays partial items. Read-only at run time.

    ItemData Property

    Returns or sets a specific number for each item in a ComboBox or ListBox control.

  • 8/12/2019 Visual Basic Programming Aan

    12/112

  • 8/12/2019 Visual Basic Programming Aan

    13/112

    VISUAL BASIC

    13

    Returns or sets a value indicating the display type and behavior of the control. Read only at runtime.

    TabIndex Property

    Returns or sets the tab order of most objects within their parent form.

    TabStop Property

    Returns or sets a value indicating whether a user can use the TAB key to give the focus to anobject.

    Tag Property

    Returns or sets an expression that stores any extra data needed for your program. Unlike otherproperties, the value of the Tag property isn't used by Visual Basic; you can use this property toidentify objects.

    Text Property

    ComboBox control (Style property set to 0 [Dropdown Combo] or to 1 [Simple Combo]) andTextBox control returns or sets the text contained in the edit area.

    ComboBox control (Style property set to 2 [Dropdown List]) and ListBox control returns theselected item in the list box; the value returned is always equivalent to the value returned by theexpression List(ListIndex). Read-only at design time; read-only at run time.

    Visible Property

    Returns or sets a value indicating whether an object is visible or hidden.

  • 8/12/2019 Visual Basic Programming Aan

    14/112

    VISUAL BASIC

    14

    2. PROGARMMING IN VB

    2.1 General Terms used in VB

    Application

    A collection of code and visual elements that work together as a single program.

    Developers can build and run applications within the development environment, whileusers usually run applications as executable files outside the developmentenvironment.

    procedureA sequence of code statements executed as a unit. The term procedure refers to bothSub and Function procedures.

    procedure levelThe location of statements within a Sub or Function procedure.

    variableA named storage location capable of containing a certain type of data that can bemodified during program execution. Each variable has a unique name that identifiesit within its level of scope. Variable names must be limited to 40 characters, mustbegin with an alpha character, cannot contain an embedded period, and cannot havethe same scope as a procedure name.

    Variable declarations in Visual basic take the form of Dim statements. In oneof its simplest forms, a Dim declaration appears as

    Dim variableNameAsdataType

    For Example, the following statements

    module variableA variable declared outside of a procedure (using the Dim statement) and visible in allprocedures in the module.

    type-declaration characterA character appended to a variable name indicating the variable's data type. Bydefault, variables are of type Variant unless a corresponding Deftype statement ispresent in the module.

    Character Data Type

    % Integer& Long! Single# Double@ Currency$ String

    event

  • 8/12/2019 Visual Basic Programming Aan

    15/112

    VISUAL BASIC

    15

    An action recognized by an object, such as clicking the mouse or pressing a key, andfor which you can write code to respond. Events can occur as a result of user actionor program code, or they can be triggered by the system.

    event procedureA procedure automatically invoked in response to an event initiated by the user,

    program code, or triggered by the system.

    2.2 Variables

    Data StructuresIn a programming language, the word structure has several important meanings. Astructured language encourages a modular approach to writing code, where programsare organised in to small, self-contained tasks. Visual Basic has all the elements of awell-structured-language, including a productive variety of data structures andcontrol structures. These are the topics of this section.A data structure gives you convenient ways to organise and store information in a

    program. Two commonly used data structure in Visual Basic are arrays and user-defined types. A variable belonging to a user-defined type is sometimes known as arecord variable:

    An arrayis a list, a table, or another multidimensional arrangement of data items,all represented by a single variable name. In programs that works with largeamounts of interrelated information, arrays are an indispensable way of organisingdata.

    A user-defined type enables you to create record variables that represent multiplevalues of different types. This type of structure is ideal for use in databaseapplications.

    A programming language also has control structures that you can use to define thedirection and flow of your program. Control structures include procedures, loops, anddecisions:

    procedures allow you to divide your code into small, cogent, usable blocks ofcode that are easy to understand and revise if necessary. A sub procedure inVisual Basic performs a discrete well defined tasks; a functional

    2.3 Programming Fundamentals

    Visual Basic is a complete programming language that supports the structured

    programming constructs found in most other modern programming language. Thissection introduces the essential components of the Visual Basic Language.

    2.3.1 Structure of a Visual Basic Application

    Your application can contain form modules (.FRM) and code modules (.BAS),as well as custom controls (.VBX). A form module contains the visual elements of aform, including all the controls on the form and the Basic code. You must have atleast one code or form module. By default, your project contains a single formmodule, but you can add additional form and code modules.

  • 8/12/2019 Visual Basic Programming Aan

    16/112

  • 8/12/2019 Visual Basic Programming Aan

    17/112

  • 8/12/2019 Visual Basic Programming Aan

    18/112

  • 8/12/2019 Visual Basic Programming Aan

    19/112

    VISUAL BASIC

    19

    Call MultiBeep(3)

    2.4.3 Function Procedures

    The syntax for a Function procedure is:

    Functionprocedurename(arguments) [Astype] statements

    EndFunction

    The arguments for a Function procedure work in exactly the same way as thearguments for a Subprocedure. Aside from the Function keyword, there are3 threedifference between Suband Functionprocedures:

    You always use parentheses with each Function call (You cannot use the Callstatement to call a Functionprocedure)

    Function procedures have data types, just as variables do. This determines thetype of the return value. ( In the absence of as Asclause, the type is the defaultVariant type unless heprocedurenamehas a type-declaration character).

    You return a value by assigning it to the procedurename itself. When theFunction procedure returns a value, this value is then used as part of a largerexpression.

    For example, you could write a function that calculates the third side, or hypotenuse,of a triangle given the other two sides:

    Function Hypotenuse (A,B)Hypotenuse = Sqr( A ^ 2 + b ^ 2 )

    End Function

    You call a Functionprocedure the same way you call any of the built-in functions inVisual Basic:

    Label1.Caption = Hypotenuse ( Val(Text1.txt), Val(Text2.Text))

    x = Hypotenuse(Width, Height)

    2.4.4 Public and Private Procedures

    The procedures in a form areprivateto that form; you can call them from within theform, but the code in other form or code modules cannot call them. The procedures ina code module arepublic; they can be called from anywhere else your application.

    Because the procedures in a form are private, you can have procedures with the samename in different forms. This is why each form can have form event procedures withthe same name (such as Form_Load). The public procedures in code modules must beunique across all code modules.

  • 8/12/2019 Visual Basic Programming Aan

    20/112

  • 8/12/2019 Visual Basic Programming Aan

    21/112

  • 8/12/2019 Visual Basic Programming Aan

    22/112

  • 8/12/2019 Visual Basic Programming Aan

    23/112

    VISUAL BASIC

    23

    3. INTRODUCTION TO BOUND CONTROLS

    3.1 IntroductionBound controls provide access to specific data in your database. Bound controls that manage a singlefield typically display the value of a specific field in the current record. Data-bound controls are thedata-aware controls through which you access information in a database. When a control is bound tothe data control, Visual Basic applies field values from the current database record to that control. Inturn, the control displays data to you and accepts your changes. If you change data in a bound control,those changes can be automatically written to the database as you move to another record.Visual Basic supports several built-in controls that you can bind to the data control. Other data-awarecontrols are available from third parties and in the Professional and Enterprise editions of Visual Basic.

    The DataSource property of a bound control specifies a valid Data control name, and the DataFieldproperty specifies a valid field name in the Recordset object created by the Data control. Together,these properties specify what data appears in the bound control. DataField sets a value that binds acontrol to a field in the current record

    Visual Basic supports several built-in (intrinsic) controls that you can bind to the data control, as wellas several data-bound ActiveX (.ocx) controls (formerly called custom or OLE controls). Many other

    data-aware controls are available from third parties and in the Professional and Enterprise editions ofVisual Basic.

    3.2 Data Control

    Data Control Provides access to data stored in databases using any one of three types of Recordsetobjects. The Data control enables you to move from record to record and to display and manipulatedata from the records in bound controls. Without a Data control or an equivalent data source controllike the RemoteData control, data-aware (bound) controls on a form cant automatically access data.The data control is used to create simple database applications without writing any code. It can also beused to create more full-featured applications that give you a high degree of control over your data.Figure shows a data control

    Figure 2 Data Control

    The data-bound list, data-bound combo, data-bound grid, and Microsoft FlexGrid controls are allcapable of managing sets of records when bound to a data control. All of these controls permit severalrecords to be displayed or manipulated at once. You can perform most data access operations using theData control without writing any 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 oneither side of the current record. The Data control performs all operations on the current record. If theData control is instructed to move to a different record, all bound controls automatically pass anychanges to the Data control to be saved in the database. The Data control then moves to the requestedrecord and passes back data from the current record to the bound controls where its displayed.

    The intrinsic picture, label, text box, check box, image, OLE container, list box and combo boxcontrols are also data-aware and can be bound to a single field of a Recordset managed by the datacontrol.

    3.3 TYPES OF CONTROL

    3.3.1 Intrinsic Controls

    The standard bound controls that you can use with the data control include the following: Check box Image Label

  • 8/12/2019 Visual Basic Programming Aan

    24/112

    VISUAL BASIC

    24

    Picture box Text box List box Combo box OLE container control

    Check BoxThe check box control displays a check mark when it is selected. It is commonly used to present aYes/No or True/False selection to the user. You can use check box controls in groups to displaymultiple choices from which the user can select one or more.

    The check box control is similar to the option button control in that each is used to indicate a selectionthat is made by the user. They differ in that only one option button in a group can be selected at a time.With the check box control, however, any number of check boxes may be selected.A check box indicates whether a particular condition is on or off. You use check boxes in anapplication to give users true/false or yes/no options. Because check boxes work independently of eachother, a user can select any number of check boxes at the same time. For example in Figure Male andMarried can both be checked which can be bound to a data filed which stores the information inBoolean fields .

    The Click event for the check box occurs as soon as you click the box. Thisevent procedure tests to see whether the check box has been selected (that is,if its Value = vbChecked).

    Figure 3.1.1 Check boxes

    Image Controls

    The image control is used to display graphics. Image controls can display graphics in the followingformats: bitmap, icon, metafile, enhanced metafile, or as JPEG or GIF files.

    Figure 3.1.2 The image controlIn addition, image controls respond to the Click event and can be used as a substitute for commandbuttons, as items in a toolbar, or to create simple animations. The Image control uses fewer systemresources and repaints faster than a PictureBoxcontrol, but it supports only a subset of the PictureBoxproperties, events, and methods.

    Picture BoxThe primary use for the picture box control is to display a picture to the user. The actual picture that isdisplayed is determined by the Picture property. The Picture property contains the file name (andoptional path) for the picture file that you wish to display.

    Figure 3.1.3 The Picture Box controlThe picture box control can also be used as a container for other controls. Like the frame control, youcan draw other controls on top of the picture box. The contained controls move with the picture boxand their Top and Left properties will be relative to the picture box rather than the form.A common use for the picture box container is as a toolbar or status bar. You can place image controls

    on it to act as buttons, or add labels to display status messages.

    Label ControlLabel controls are used to display text and cannot be edited by the user. They are used to identifyobjects on a form provide a description of what a certain control will do if clicked, for example or at run time, they can display information in response to an event or process in your application.

    Figure 3.1.4 Label ControlLabels are used in many instances, for many different purposes. Most commonly, they are used to labelcontrols that don't have their own Caption properties. For example, you can use the label control to adddescriptive labels to text boxes, list boxes, combo boxes and so on. They can also be used to adddescriptive text to a form, for example, to provide the user with Help information.

  • 8/12/2019 Visual Basic Programming Aan

    25/112

    VISUAL BASIC

    25

    You can also write code that changes the text displayed by a label control in response to events at runtime. For example, if your application takes a few minutes to process a change, you can display aprocessing-status message in a label.Text BoxLabel and text box controls are used to display or enter text. Use labels when you want your applicationto display text on a form, and text boxes when you want to allow the user to enter text. Labels containtext that can only be read, while text boxes contain text that can be edited.Text boxes are versatile controls that can be used to get input from the user or to display text. Textboxes should not be used to display text that you don't want the user to change, unless you've set theLocked property to True.The actual text displayed in a text box is controlled by the Text property. It can be set in three differentways: at design time in the Property window, at run time by setting it in code, or by input from the userat run time. The current contents of a text box can be retrieved at run time by reading the Text property.Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. Amultiple-line text box automatically manages word wrap as long as there is no horizontal scroll bar.The ScrollBars property is set to 0-None by default. Automatic word wrap saves the user the trouble ofinserting line breaks at the end of lines. When a line of text is longer than what can be displayed on aline, the text box wraps the text to the next line.Line breaks cannot be entered in the Properties window at design time. Within a procedure, you createa line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and 10). You canalso use the constant vbCrLf to insert a carriage return/linefeed combination.

    The text box control is used to display information entered by the user at run time, or assigned to theText property of the control at design or run time.A TextBoxcontrol, sometimes called an edit field oredit control, displays information entered at design time, entered by the user, or assigned to the controlin code at run time.

    Figure 3.1.5 The Text Box controlIn general, the text box control should be used for editable text, although you can make it read-only bysetting its Locked property to True. Text boxes also allow you to display multiple lines, to wrap text tothe size of the control, and to add basic formatting.Text entered into the text box control is contained inthe Text property. By default, you can enter up to 2048 characters in a text box. If you set theMultiLine property of the control to True, you can enter up to 32K of text.

    Multiple-Line Text Boxes and Word WrapBy default, a text box displays a single line of text and does not display scroll bars. If the text is longerthan the available space, only part of the text will be visible. The look and behavior of a text box can bechanged by setting two properties, MultiLine and ScrollBars, which are available only at design time.

    List BoxA list box control displays a list of items from which the user can select one or more.

    Figure 3.1.6 The list box control

    List boxes present a list of choices to the user. By default, the choices are displayed vertically in asingle column, although you can set up multiple columns as well. If the number of items exceeds whatcan be displayed in the list box, scroll bars automatically appear on the control. The user can then scrollup and down, or left to right through the list.Visual Basic includes both standard and data-bound versions of the list box control. While bothversions of the list box control allow you to display, edit, and update information from most standardtypes of databases, the data-bound list provides more advanced data access features. The data-boundlist box control also supports a different set of properties and methods than the standard list boxcontrol.

    Combo Box

  • 8/12/2019 Visual Basic Programming Aan

    26/112

    VISUAL BASIC

    26

    A combo box control combines the features of a text box and a list box. This control allows the user toselect an item either by typing text into the combo box, or by selecting it from the list.

    Figure 3.1.7 The Combo Box control

    Combo boxes present a list of choices to the user. If the number of items exceeds what can be displayedin the combo box, scroll bars will automatically appear on the control. The user can then scroll up anddown or left to right through the list.

    When to Use a Combo Box Instead of a List Box

    Generally, a combo box is appropriate when there is a list of suggested choices, and a list box isappropriate when you want to limit input to what is on the list. A combo box contains an edit field, sochoices not on the list can be typed in this field.

    Combo Box Styles

    There are three combo box styles. Each style can be set at either design or run time and uses values, orequivalent Visual Basic constants, to set the style of the combo box.

    Style Value ConstantDrop-down combo box 0 vbComboDropDownSimple combo box 1 vbComboSimple

    Drop-down list box 2 vbComboDropDownList

    In addition, combo boxes save space on a form. Because the full list is not displayed until the userclicks the down arrow (except for Style 1, which is always dropped down), a combo box can easily fitin a small space where a list box would not fit.You can also use the data-bound list box and data-bound combo box controls with a single data control.To do this, set both the DataSource and RowSource properties to the same data control, and set theDataField and BoundColumn properties to the same field in the data controls recordset. In this case,the list will be filled with ListField values from the same recordset that is updated. If a ListFieldproperty is specified, but no BoundColumn property is set, BoundColumn will automatically be set tothe ListField field.A common use of these controls is to build a list of items based on a database query from which a usercan select or enter a value, or in the case of data-bound combo box, to edit the selected field. When an

    item in the list is selected, its associated BoundColumn property value is made available to the datacontrol specified by the DataSource property. Once the data control moves to another record or isotherwise updated, the recordset is updated with the selected or edited text.

    OLE controlYou can link or embed any object that supports Automation (formerly called OLE Automation) into theOLE container control. Using this control, your Visual Basic application can display and manipulatedata from other Windowsbased applications, such as Microsoft Excel and Microsoft Word forWindows.

    Figure 3.1.8 The OLE container controlThe OLE container control enables you to add insertable objects to the forms in your Visual Basic

    applications. With the OLE container control, you can: Create a placeholder in your application for an insertable object. At run time you can createthe object that is displayed within the OLE container control or change an object you placed within theOLE container control at design time. Create a linked object in your application. Bind the OLE container control to a database using the Data control.You can bind the OLE container control to data stored in the Microsoft Jet database engine orMicrosoft Access database. You may want to do this, for example, if you have a database with a tableof employee pictures. If the pictures are stored as objects, you can bind them to the OLE containercontrol and display them on a form as each record is accessed with the data control. To bind data to oneof these databases, specify the source of data (recordset name) in the DataSource property and the fieldname from that data source in the DataField property of the OLE container control. When displaying an

  • 8/12/2019 Visual Basic Programming Aan

    27/112

    VISUAL BASIC

    27

    object from a database, the OLE container control allows the user to activate, edit, and update theobject. As with any bound control, the updated object is automatically written back to the databasewhen the record position is changed.

    3.3.2 ActiveX Controls

    In addition to the intrinsic bound controls, Visual Basic also provides the following ActiveX controlsthat can be added to your project:

    Data-bound list box Data-bound combo box MSFlexGrid Apex Data-Bound Grid (DBGrid)

    For complex interfaces, several of these ActiveX controls provide added functionality to let you displaywhole groups of records, such as lists, tables, or entire recordsets. These include the list box, combobox, and MSFlexGrid controls.In addition, three special controls allow you to accomplish complex database display and updatingtasks with multiple recordsets and fields. These are the data-bound list and combo box controls and theDBGrid control.Data Access ControlsBasically, you can use Remote Data Objects similarly to the way you use the Microsoft Jet database

    engine Data Access Objects (DAO), and the RemoteData control is similar to the Data control. WithRDO, you can submit queries, create a result set or cursor, and process the results from the query usingdatabase-independent object-oriented code.Using the RemoteData control, you can create a form containing the same bound controls recognizedby the Data control and process a result set with little or no code. You can take your existingapplications that use DAO and the Data control and convert them to use RDO and the RemoteDatacontrol with a few changes. There are some differences, however, because RDO is implemented anddesigned for use with strictly relational databases. RDO has no query processor of its own; it dependson the data source to process all queries and create the result sets. The data objects themselves are builtfrom the result sets and cursors returned by the ODBC driver. The data control is used to connect to a database. Think of it as a pipeline between thedatabase and the other controls on your form. Its properties, methods, and events allow you to navigateand manipulate external data from within your own application. The DBList control is similar to the list box control. When used in conjunction with a data

    control, it can be automatically filled with a list of data from a field in an external database. The DBCombo control is like a combination of the DBList and a text box. The selected text inthe text box portion can be edited, with the changes appearing in the underlying database. The DBGrid control displays data in a grid or table. When used in conjunction with a datacontrol, it presents fully editable data from multiple fields in an external database. The MSFlexGrid control is a unique control for presenting multiple views of data. Think of itas a combination of a grid and a tree or outline control. At run time, the user can rearrange columns androws to provide different views of the data.Most bound controls are characterized by three data-aware properties: DataChanged, DataField, andDataSource.PropertyDescription

    DataChanged Indicates whether a value displayed in a bound control has changed.DataField Specifies the name of a field in the recordset created by the data control.

    DataSource Specifies the name of the data control to which the control is bound.

    The steps in adding bound controls to your application are:1. Draw the bound control on the same formas the data control to which it will be bound.2. Set the DataSource property to specify the data control to which it will be bound.3. Set the DataField property to a valid field in the data controls recordset.

    If the database is available at design time, a list of valid fields will be displayed in the DataFieldSettings box in the Properties window. If the database is not available at design time, youll need toprovide a valid field name at run time before data values will be posted to the control from thedatabase.

  • 8/12/2019 Visual Basic Programming Aan

    28/112

  • 8/12/2019 Visual Basic Programming Aan

    29/112

    VISUAL BASIC

    29

    The DBCombo control differs from the standard ComboBox control. While the ComboBox control listis filled using the AddItem method, the DBCombo control is automatically filled with data from a fieldin the Recordset object of a Data control to which it is attached. The standard ComboBox control mustbe populated manually by using the AddItem method. In addition, the DBCombo control has the abilityto update a field within a related Recordset object which may reside in a different Data control.The DBCombo control also supports an automated search mode that can quickly locate items in the listwithout additional code.

    The following example uses the data-bound combo box control to create a data entry screen for theTitles table of the Biblio.mdb sample database(This MDB is supplied with Access/VB). It lets the userenter new titles and assign them to existing publishers by providing a lookup table of all the publishersnames. When users get to the Publisher field in the entry form, they can choose a publisher from a listbox. When they select a publisher, that publishers PubID field is copied into the PubID field of theTitles table.

    To create a lookup table with the data-bound combo box control1. Add a data-bound combo box control and two data controls to your form.2. In the Properties window, set the first data control (Data1) properties to create a table-type

    recordset against the Titles table.3. Set the second data control (Data2) properties to a create a snapshot-type Recordset object

    against the Publishers table, using the following SQL Query:SELECT PubID, Name FROM Publishers ORDER BY PubID

    4. Set the DataSource property for the data-bound combo box to the first data control (Data1).The DataField property should be set to the PubID field of the Titles table. This binds thedata-bound combo box control to update the Titles recordset.

    5. Set the RowSource property for the data-bound combo box to the second data control(Data2).

    6. Set the BoundColumn property for the data-bound combo box to the PubID field of thePublishers table. This sets the data-bound combo box control to use the PubID field of thesecond data controls recordset (Publishers) when it updates the DataField of the first datacontrols recordset (Titles).

    7. Set the ListField property to the Name field of the Publishers table. Note that the ListFieldproperty pull-down menu is derived from the data control specified by the RowSource property. Thisspecifies that the Name field will be used to fill the data-bound combo boxs list.

    The DataField and the BoundColumn fields should be identical, but in different tables; that is, thesefields should reflect a relation between the two tables.

    DBGrid ControlYou can use the Apex Data-Bound Grid (DBGrid) control to quickly and easily display and browsethrough all the records in a database table. This can be accomplished in minutes without writing code.The Apex Data-Bound Grid (DBGrid) control displays records from the underlying Recordset object atrun time. There is always a single current record in the DBGrid control, even if multiple rows in thecontrol are selected. The current record corresponds to the data controls current record and can be setor retrieved with the DBGrid controls Bookmark property.As with other data-bound controls, when you change a record (or any field in a record) in the DBGrid,the underlying recordset is updated when you move to a new record (row), assuming that it is updatableand the DBGrid controls AllowUpdate property is set to True.

    Before using the DBGrid, you must make sure the control is available to the project. If necessary, add iton the Controls tab in the Components dialog box, available from the Project menu.

    To use DBGrid to display and browse through an existing database table, follow these steps:1. Add a data control to a new form, and set its DatabaseName and RecordSource properties to

    the database and table you want to display.2. Add a DBGrid control to the form, and set its DataSource property to the data control you just

    created.3. Run the application.

    When your program runs, the database table you specified is displayed in the DBGrid, complete withcolumn headers (from the data controls recordset) and scroll bars. You can immediately scroll through

  • 8/12/2019 Visual Basic Programming Aan

    30/112

    VISUAL BASIC

    30

    all the records and fields of the table. In addition, you can edit any cell in the table, and it willautomatically be updated when you move to a new row (assuming that the underlying recordset isupdatable and the DBGrid controls AllowUpdate property is set to True). With the AllowAddNew andAllowDelete properties set to True, you can delete records by selecting and deleting the entire row.

    Displays and enables data manipulation of a series of rows and columns representing records and fieldsfrom a Recordset object. The data-aware DBGrid control appears similar to the Grid control; however,you can set the DBGrid control's DataSource property to a Data control so that the control isautomatically filled and its column headers set automatically from a Data control's Recordset object.The DBGrid control is really a fixed collection of columns, each with an indeterminate number ofrows.

    Figure 3.2.4 DBGrid ControlEach cell of a DBGrid control can hold text values, but not linked or embedded objects. You canspecify the current cell in code, or the user can change it at run time using the mouse or the arrow keys.Cells can be edited interactively, by typing into the cell, or programmatically. Cells can be selectedindividually or by row.If a cell's text is too long to be displayed in the cell, the text wraps to the next line within the same cell.To display the wrapped text, you must increase the cell's Column object's Width property and/or theDBGrid control's RowHeight property. At design time, you can change the column width interactivelyby resizing the column or by changing the column's width in the Column object's property page.

    Use the DBGrid control's Columns collection's Count property and the Recordset object's RecordCountproperty to determine the number of columns and rows in the control. A DBGrid control can have asmany rows as the system resources can support and about 1700 columns.When you select a cell, theColIndex property is set, thus selecting one of the Column objects in the DBGrid object's Columnscollection. The Text and Value properties of the Column object reference the contents of the currentcell. The data in the current row can be accessed using the Bookmark property, which provides accessto the underlying Recordset object's record. Each column of the DBGrid control has its own font,border, word wrap, color and other attributes that can be set without regard to other columns. At designtime, you can set the column width and row height and establish columns that are not visible to theuser. You can also prevent users from changing the formatting at run time.The DataMode property controls how the data is handled for the DBGrid control. In unbound mode,you are responsible for maintaining data and supplying the DBGrid control with the appropriate datawhen requested through the unbound events. In bound mode, the data is retrieved and updated

    automatically using the Data control's Recordset. Normally, the unbound mode of the DBGrid controlis used when displaying data that is not stored in a database accessible by the Microsoft Jet DatabaseEngine. You can use the unbound mode for whatever type of data you have available. For example, youcan use the unbound mode of the DBGrid control to display data from a proprietary database format oruse it to manage data that you keep track of in a text file.

  • 8/12/2019 Visual Basic Programming Aan

    31/112

  • 8/12/2019 Visual Basic Programming Aan

    32/112

  • 8/12/2019 Visual Basic Programming Aan

    33/112

  • 8/12/2019 Visual Basic Programming Aan

    34/112

    VISUAL BASIC

    34

    The syntax for the CreateSnapshot method is:CreateSnapshot (source [, option])

    The source for a Snapshot can be a table name, an attached table name, QyeryDef object name, or SQLstatement expressed as a string. The options part controls parameters such as read/write privileges,table update procedures, and SQL query processing.You can create a Snapshot variable on any table, on the result of any query, on any Dynaset, or onanother Snapshot. You cannot execute the Edit, AddNew, or Update methods against Snapshot.

    4.3 Selecting Records

    When you want to further limit the scope of records returned by a Dynaset or Snapshot you can:

    Create a new Dynaset or Snapshot after having set the Filter property on an existing Dynaset orSnapshop.

    Include an SQL query that limits the records as the argument to a CreateDynaset orCreateSnapshot method executed against an existing Dynaset or Snapshot.

    For example, the following code filters the Titles table to produce a Dynaset that contains only Titlesthat have the string SQL embedded in the Name, and then sorts the titles by the Date Published andthe first letter of the Name:

    Dim db as database, somedata as Dynaset, sortdata as dynasetSet db = OpenDatabase(BIBLIO.MDB)

    Set somedata = db.CreateDynaset(Titles)

    somedata.Filter = [Name] LIKE *SQL*

    somedata.Sort = [Date Published], left([Name], 1)

    Set sortdata = somedata.CreateDynaset()

    You cant set a Filter on a Table variable. If you want to restrict the records in a Table, you must createa Dynaset or Snapshot variable on the table.

    Closing Recordset Variables

    To close a recordset variable, you use the close method. Visual Basic automatically closes a Table,Dynaset, or Snapshot if you destroy the associated variable.

    4.4 Positioning the Current Record in a Recordset

    A recordset can have from zero to any number of records, Visual Basic makes only one recordsetrecord available at a time. This record is the current record; you must make a record current before youcan access its data. To make a specific record current, you need to use Seekmethod or one of the Moveor Find methods.

    The current record will become undefined and unusable when the current record is positioned asfollows:

    Ahead of the first record, when the BOF property is True. Behind the last record, when the EOF property is True. Over a record that has been deleted, by not using a Move method or bookmark after records are

    deleted or by positioning to a record that another user deleted.

    When using Seek or one of the Find methods and no records could be found that match thecriterion or key value. If the NoMatch property is True after using one of these methods, you maybe positioned to a valid record, but there is no guarantee of that. It is best to save the valid currentrecord in a bookmark and restore the current record to the bookmark value after one of thesemethods fails.

    In a recordset where there are no records. This applies Whether you create a recordset variablewith no records or delete all records in a table.

    Using the Move MethodsVisual Basic provides four Move methods for changing the current record.

    Mehtod PurposeMoveFirst Makes the first record the current record

  • 8/12/2019 Visual Basic Programming Aan

    35/112

    VISUAL BASIC

    35

    MoveLast Makes the last record the current recordMoveNext Makes the next record the current recordMovePrevious Makes the previous record the current record

    Using the Find MethodsRather than looping through all the records in a Dynaset or Snapshot, you can make your code moreeffeicient by finding only those records that match given criteria. In most cases, you should use a queryto select a general subset of records for a Dynaset or Snapshot, then use the Find methods to searchwithin that subset. Each method takes a criterion argument and searches through the Dynaset orSnapshot for matches. The find methods cannot be used on Table objects.Method What it finds Starting partFindFirstcriteria First record matching criteria First record in recordset.FindLastcriteria Last record matching criteria Last record in recordset.FindNextcriteria Next record matching criteria Current record.FindPreviouscriteria Previous record matching criteria Current record.

    Use the Seek methodThe Seek method provides a dramatically faster way of finding records in an indexed Table variable.The Seek method finds data in a Table object using the current index, as defined by the Index propertyof the Table variable. If there is no suitable index to use, you must create one in order to use the Seekmethod. The Seek method takes a variable number of arguments, the first of which always a

    comparison string that indicates the kind of comparison that will be performed.

    Comparison string Find first record= Equal to the key values.> Greater than the key values.>= Greater than or equal to the key values.< Less than the key values.=, M

    If pubs.NoMatch then

    msgbox not found

    else

    msgbox pubs(Name) & & pubs(Zip)

    endifpubs.close

    db.close

    Using BookmarksThe Bookmark property of a recordset object enables you to mark your place in a recordset so you canreturn to it later. For example, you can keep a pointer to the current record by saving a bookmarkbefore you use Seek or one of the Find methods to move to another record.

    Function ShowPublisher()

    Dim ds as Dynaset, MyBookmark

    Set ds = data1.Recordset

    MyBookmark = ds.Bookmark

    ds.FindFirst [Publisher] = ds.PubIdIf ds.Nomatch then

    MsgBox No such publisher

    ds.Bookmark = MyBookmark

    End IF

    End Function

  • 8/12/2019 Visual Basic Programming Aan

    36/112

    VISUAL BASIC

    36

    4.5 Using Recordsets to Manipulate Data

    Once youve defined a recordset variable, you can access its data.Changing RecordsOnce youve found a record, you can change its contents. Changing the value of a record with code is athree-step process.

    Use the Edit method to prepare the current record for editing.

    Assign new values to the fields you want to change in the current record.

    Use the Update method to save the changes to the current record.Deleting RecordsTo delete a record, you use the Delete method.Syntax is:

    Recordsetvariable.Delete

    Adding New RecordsYou can append or insert new records in an updatable Table or Dynaset. As with updating records,adding a new record is a three-step process:

    Use the AddNew method to create a new record. The current record pointer is saved.

    Assign new values to the fields in the new record.

    Use the Update method to save the new record.Locking DataWhen multiple users are attempting to change the same data, there is an obvious conflict-which user

    actually updates the data? The solution to this conflict, common to all multiuser database managementsystems, is locking. By locking data thats being changed by one user, the database can ensure that noother user simultaneously changes that same data.You can do Lock Database by setting exclusive part of the OpenDatabase function to True:

    4.6 Using QueryDef Variables

    A QueryDef is an object variable that contains an SQL statement that describes a query. You can use aQueryDef to save a predefined query in the database. QueryDef do not store data - they store thedefinition of query used to retrieve data.You declare a QueryDef the same way you declare other object variables:

    Dim Q as QueryDef

    You can run the query by creating a Dynaset variable on the QueryDef variable or by using the Execute

    method.Creating a New QueryTo create a new QueryDef, you use the CreateQueryDef method to create a query within the specifieddatabase, then assign it to a declared QueryDef variable:

    Dim db as Database, Q as QueryDef

    Set db = OpenDatabase(Currency.MDB)

    Set Q = db.CreateQueryDef(New Query)

    To define the query, you assign a valid SQL string to the SQL property of the QueryDef variable:Q.SQL = SELECT Country FROM dbCurrency;

    You can also create and define the query in a single step by providing the SQL string when you createthe query:

    Set Q=db.CreateQueryDef(New Query, SELECT Country FROM dbCurrency;)

    Running a Query

    Once youve defined a query with a valid SQL string, you can run the query by creating a Dynaset onthe QueryDef variable:

    Set DataRecs = Q.CreateDynaset()

    Closing a QueryWhen youre finished with a QueryDef variable, its good programming practice to close it:

    Q.Close

    Deleting a QueryTo delete a query, you use following code:

    db.DeleteQueryDef New Query

  • 8/12/2019 Visual Basic Programming Aan

    37/112

    VISUAL BASIC

    37

    4.7 Data Control and Bound Controls

    With the data control, you can create applications to display, edit, and update information from manytypes of existing databases. To use the data control in a Visual Basic program, you add an instance ofthe control to a form and then set three essential properties that define a specific database connection

    The connect property indicates the type of database youll attach to the program; Access is thedefault.

    The DatabaseName property is the file name of the database on disk. The RecordSource property is the name of a table in the database.

    Once youve defined the properties of the data control, you next begin adding bound controls to thesame form. Each bound control is designated to represent a field from the table youve selected as theRecordSource property of the data control. For example, you can add bound labels to display field data,or bound text boxes to allow editing of fields. Two important properties define a bound controls:

    The DataSource property is the name of the data control to which the control will be bound. Inother words, the bound control will display a field from the data controls RecordSource table.

    The DataField property is the name of the field that the bound control will represent.

    In addition to the label and text box, you can use the list box, combo box, picture box, image and check

    box as bound controls. Once youve designed a form that contains a data control and one or morebound controls, your program is ready to run. When you start the program, the bound controls displayfield information from the first record in the designated table. The data control provides buttons forscrolling from one record to the next in the database. The operations you can perform on the databasedepend on the types of bound controls youve added to your form. Some bound controls, such aslabels, simply display field data; others, such as text boxes, provide both read and write capabilities.

    Adding a data control to a form.In the following exercise youll use this approach to create the Currency Input program as a tool forentering and revising records in the Exchange table of the Currency.MDB database. As youll see , theprogram consists of a form containing a data control, three bound text boxes, and three labels. Theprogram contains no code. To develop the project, you simply add the controls to a form and set theappropriate properties:

    1. Start a new project in Visual Basic. Open a new form.2. Press F4 to activate the Properties window.3. Pull down the File menu and choose Save File As. Enter CurrInDB as the file name for the name

    for the form, and click save; as usual, Visual Basic adds FRM as the extension.4. Double-click the data control in the Toolbox. An instance of the data control appears on the form.

    5. Press F4 and enter Currency.MDB as the controls Caption property.6. Select the DatabaseName property for the data control, giving you the opportunity to select an

    Access database file to connect to your program.7. Select the Name property and enter dbCurrency as the name of the data control.8. Scroll to the RecordSource property. Enter the table name.9. Add three labels and three text boxes to the form.10. Select the first of the three text boxes in the form and pressF4 to activate the Properties window.

    Scroll up to the DataSource property, and enter the name of the data control youve added to thisform, dbCurrency.

    11. Select the DataField property, and enter the names of the three fields in the Exchange table -Country, Currency, and InDollars.

  • 8/12/2019 Visual Basic Programming Aan

    38/112

    VISUAL BASIC

    38

    12. Your program is complete. Save the Project.

    Now youre ready to run the program and use it to append records to the Exchange table of theCurrency.MDB database. The program connects to the database and, displays the record that youvealready entered into the table.

    To add a new record, click the Next Record button. The program presents a set of blank fields in whichyou can enter the information for a new record

    When you finish entering the last record, click the Close button (X) at the upper-right corner of thewindow to end the program performance.

    4.8 Programming with the Data Control

    During runtime, a data control is associated with a Recordset object, which represents all the records inthe corresponding database table. In code, you use the data controls Recordset property to refer to thisobject:

    Data1.Recordset

  • 8/12/2019 Visual Basic Programming Aan

    39/112

    VISUAL BASIC

    39

    The Recordset object has properties and methods that you program can use to scroll through the table,to locate specific records, and to read fields of information:

    The Move methods (MoveNext, MovePrevious, MoveFirst, MoveLast) change the current recordin the database

    The Find methods (FindNext, FindPrevious, FindFirst, FindLast) look for a record that matches aparticular search criterion. When a matching record is found, it becomes the current record.

    The EOF property indicates whether the program has moved past the last record in the databasetable. The Fields property represents the collection of all the fields in the table. You can use the Fields

    (fieldName) notation to identify a specific field. The Value property of a field provides access toa data item stored in the current record.

    Create a new form that includes Combo box, two Option buttons, text box and command buttons.Give the Name of the form is frmCurrExc.

    4.8.1 Stepping through the Database Records

    Dim db As database, dt As table

    The Form_Load procedure begins its work by declaring variables as database and table.

    Set db = OpenDatabase("c:\temp\currency.mdb")This statement is used to Open a Database Currency.MDB

    Set dt = db.OpenTable("dbCurrency")

    This statement is used to Open a Table dbCurrencydt.MoveFirst

    This statement is used to move to the First record of the table.Do Until dt.EOF

    combo1.AddItem dt.Fields("Country").Value

    dt.MoveNext

    Loop

    The main task of the Form_Load procedure is to read the Country field from each record of theRecordset and to copy the field to the drop-down list of the combo box. This takes place in a Do loop

    that steps through the database table from the first record to the last: The While loop continues readingas long as the Recordsets EOF property is False. The Fields(Country).Value notation supplies thedata item stored in the Country field of the current record. There are actually several ways to refer tothis value. The complete reference is

    dbCurrency.Recordset.Fields(Country).Value

    But you can abbreviate this reference in the following ways:

    dbCurrency.Recordset.Fields(Country)

    ordbCurrency.Recordset(Country)

    Then the record pointer needs to be moved down to the next record in the database table. A call to the

    MoveNext method performs this task:

    .MoveNext

    4.8.2 Searching for a Database Record

    When the user pulls down the Country list and choose the name of a country, the eventprocedure named combobox_click takes control. This procedures fist job is to find the recordcorresponding to the users selection from the list. Then it reads the three fields of that record, and usesthe field data to display specific information in the application window.

  • 8/12/2019 Visual Basic Programming Aan

    40/112

    VISUAL BASIC

    40

    The procedure calls the Recordset.FindFirst method to perform the search. FindFirst stepsthrough a database table, starting from the first record, and searches for a record that meets a specificsearch criterion. The Country field of the target record should have the same value as Combobox.Text -that is, the country that the user has selected from the list.

    Here is how the procedure expresses this search criterion in the call to FindFirst method:data1.Recordset.FindFirst "Country= " & "'" & combo1.Text & "'"

    The search criterion in this example is a concatenation of three strings. For example, suppose the userpulls down the Country list and chooses France from the list; in effect, the FindFirst method works likethis:

    data1.Recordset.FindFirst Country = France

    The record that meets the criterion becomes the current record in the database table.

    4.8.3 Using bound controls at Run Time

    Adding a New Record

    To add a new record, you use the data control Recordset objects AddNew method. The code looks likethis

    Data1.Recordset.AddNew

    The following code adds a new title to the Titles table of the Currency.MDB database.Data1.Databaseame = Currency.MDB

    Data1.RecordSource = dbCurrency

    Data1.Refresh

    Data1.Recordset.AddNew

    Data1.Recordset(Country) = India

    Data1.Recordset(Currency)= RupeesData1.Recordset(Value in Currency) = 37

    Data1.Recordset.Update

    Editing the Current RecordTo change data in your database, you must first make the record you want to edit the current record. Tosave your changes, simply move the current record pointer to another record, or use the Updatemethodas shown in the preceding code example.

    Data1.Databaseame = Currency.MDB

    Data1.RecordSource = dbCurrency

    Data1.Refresh

  • 8/12/2019 Visual Basic Programming Aan

    41/112

  • 8/12/2019 Visual Basic Programming Aan

    42/112

    VISUAL BASIC

    42

    The RecordSource PropertyThe RecordSource property indicates where in the database the data will be found. You can use theRecordSource property to specify one of three different sources:

    The name of a database table. The name of a Microsoft Access database query. The text of a SQL query.

    At design time you can choose from a list of database tables and queries by first specifying theDatabaseName and (if required) Connect properties. At run time, you can specify a table name or aquery name, or you can use the RecordSource property to specify a SQL query that will return a set ofrecords from your database. For example, the following SQL query returns all of the columns in theCurrency database for the Country is Germany:

    Data1.Databaseame = Currency.MDB

    Data1.RecordSource = Select * from dbCurrency where Country = Germany

    Data1.Refresh

    Closing a RecordsetThe Close method closes the recordset and frees the resources allocated to it.

    Data1.Recordset.Close

    Databases and their respective recordsets are closed when:

    You use the Close method against a specific recordset. The form containing the data control is unloaded.

    The program executes an Endstatement.

    4.9 Using SQL

    SQL (Structured Query Language) is a common idiom for working with relational data bases. You canuse SQL statements in many places in Visual Basic where you can enter the name of a table, query, orfield.For example, you can enter an SQL statement as the setting for the RecordSource property of a datacontrol to produce a list of items. Here is how you might use SQL in the Combobox_click procedure

    instead of the call to the FindFirst method:

    Data1.RecordSource = "select * from dbCurrency where Country =" & "'" & Combo1.Text &

    "'"

    Data1.Refresh

    This code uses Select statement to change the setting of the RecordSource property. Then a call to theRefresh method rebuilds the Recordset.SQL Statements

    SELECT fieldlistFROM tablenames IN databasename

    WHERE searchconditions

    GROUP BY fieldlist

    HAVING searchconditions

    ORDER BY fieldlist

    SELECT CLAUSESELECT specifies which fields you want to retrieve. You use the FROM clause to indicate whichtables contain those fields. You use the WHERE clause to indicate which records are to be retrieved.Example: Selects the Last Name and First Name fields of all records in the Employees table.

    SELECT [Last Name], [First Name]

    FROM Employees

  • 8/12/2019 Visual Basic Programming Aan

    43/112

  • 8/12/2019 Visual Basic Programming Aan

    44/112

  • 8/12/2019 Visual Basic Programming Aan

    45/112

  • 8/12/2019 Visual Basic Programming Aan

    46/112

    VISUAL BASIC

    46

    5. QUERIES

    Query is a language in which a user requests information from the database. We can use queries toView, Change and Analyze data in different ways. There are four different types of Queries.

    1. Select Queries2. Crosstab Queries

    3. Action Queries4. SQL Queries

    5.1 Select Queries

    A select query is the most common type of query. It retrieves data from one or more tablesand displays the results in a datasheet where you can update the records (with some restrictions). Youcan also use a select query to group records and calculate sums, counts, averages, and other types oftotals.

    Syntax:SELECT [ALL | DISTINCT | DISTINCTROW | [TOP n [PERCENT]]]

    FROM table

    The following two examples are equivalent and return all records from the Employees table:

    SELECT * FROM Employees:

    Omits records that contain duplicate data in the selected fields. To be included in the results ofthe query, the values for each field listed in the SELECT statement must be unique. For example,several employees listed in an Employees table may have the same last name. If two records containSmith in the Last Name field, the following SQL statement returns only one record that contains Smith

    SELECT DISTINCT LastName FROM Employees;

    If you omit DISTINCT, this query returns both Smith records. If the SELECT clause contains

    more than one field, the combination of values from all fields must be unique for a given record to beincluded in the results. The output of a query that uses DISTINCT isn't updatable and doesn't reflectsubsequent changes made by other users.

    DISTINCTROW Omits data based on entire duplicate records, not just duplicate fields. Forexample, you could create a query that joins the Customers and Orders tables on the Customer ID field.The Customers table contains no duplicate Customer ID fields, but the Orders table does because eachcustomer can have many orders. The following SQL statement shows how you can useDISTINCTROW to produce a list of companies that have at least one order but without any detailsabout those orders

    SELECT DISTINCTROW CompanyNameFROM Customers INNER JOIN OrdersON Customers.CustomerID = Orders.CustomerIDORDER BY CompanyName;

    If you omit DISTINCTROW, this query produces multiple rows for each company that hasmore than one order.DISTINCTROW has an effect only when you select fields from some, but not all,of the tables used in the query. DISTINCTROW is ignored if your query includes only one table, or ifyou output fields from all tables.

    RENAME OPERATION:

    SQL provides a mechanism for renaming both tables and fields. It uses the asclause taking the form:

  • 8/12/2019 Visual Basic Programming Aan

    47/112

  • 8/12/2019 Visual Basic Programming Aan

    48/112

    VISUAL BASIC

    48

    Inner join is used to connect two tables.Syntax:

    SELECT Field name FROM table1 INNER JOIN table2 ON table1.field1 compare

    table2.field2

    SELECT DISTINCTROW Sum(UnitPrice * Quantity) AS [Sales], FirstName & " " &LastName AS Name FROM Employees INNER JOIN(Orders INNER JOIN [Order Details]ON Orders.OrderID = [Order Details].OrderID) ON Employees.EmployeeID =Orders.EmployeeID GROUP BY FirstName & " " & LastName;

    5.2 Cross Tab Queries

    A crosstab query displays summarized values (sums, counts, and averages) from one field in a tableand groups them by one set of facts listed down the left side of the datasheet and another set of factslisted across the top of the datasheet. For an example of a crosstab query

    Syntax: Sum(expr)

    First(expr)Last(expr)

    Min(expr)Max(expr)Count(expr)Avg(expr)

    SELECT Sum(UnitPrice * Quantity)AS [Total Revenue] FROM [Order Details];

    SELECT First(LastName), Last(LastName) FROM Employees;

    The next two examples compare using the First and Last functions with simply using the Min and Maxfunctions to find the earliest and latest birth dates of Employees.

    SELECT First(BirthDate), Last(BirthDate) FROM Employees;

    SELECT Min(BirthDate), Max(BirthDate) FROM Employees;

    SELECT Count(ShipCountry)AS [UK Orders] FROM Orders WHERE ShipCountry = 'UK';

    5.3 Action Queries

    An action query is a query that makes changes to many records in just one operation. Thereare four types of action queries: make-table, delete, append, and update.

    Make-table query

    Creates a new table from all or part of the data in one or more tables. Make-table queries are helpfulfor:Creating a table to export to other Microsoft Access databases. For example, you might want to create atable that contains several fields from your Employees table, and then export that table to a databaseused by your personnel department.

    Syntax:CREATE TABLE table (field1 type [(size)] [index1] [, field2 type [(size)] [index2] [, ...]] [,

    multifieldindex [, ...]])

    This example creates a new table called MyTable with two Text fields, a Date/Time field, and aunique index made up of all three fields.

  • 8/12/2019 Visual Basic Programming Aan

    49/112

  • 8/12/2019 Visual Basic Programming Aan

    50/112

    VISUAL BASIC

    50

    INSERT INTO Employees SELECT Trainees.* FROM Trainees WHERE HireDate < Now() -30;

    Update Table

    Syntax:UPDATE table

    SET newvalueWHERE criteria;

    This example increases the UnitPrice for all nondiscontinued products from supplier 8 by 10 percent.

    UPDATE Products SET UnitPrice = UnitPrice * 1.1 WHERE SupplierID = 8 ANDDiscontinued = No;

    5.4 SQL Queries

    An SQL query is a query you create using an SQL statement. Some examples of SQL-specific queriesare the union query and subqueries.

    Union query

    This type of query combines fields (columns) from one or more tables or queries into one field orcolumn in the query's results. For example, if you have six vendors that send new inventory lists eachmonth, you can combine these lists into one result set using a union query, and then create a make-tablequery based on the union query to make a new table.

    Syntax:[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL] [TABLE] queryn [ ... ]]

    This example retrieves the names and cities of all suppliers and customers in Brazil.

    SELECT CompanyName, City FROM Suppliers WHERE Country = "Brazil" UNIONSELECT CompanyName, City FROM Customers WHERE Country = "Brazil";

    Subquery

    This type of query consists of an SQL SELECT statement inside another select query or action query.You can use subquery to:

    Test for the existence of some result from the subquery (using the EXISTS or NOT EXISTSreserved words).

    Find any values in the main query that are equal to, greater than, or less than values returned by thesubquery (using the ANY, IN, or ALL reserved words).

    Create subqueries within subqueries (nested subqueries).

    A Subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO,

    DELETE, or UPDATE statement or inside another subquery.

    Syntax:You can use three forms of syntax to create a subquery:comparison [ANY | ALL | SOME] (sqlstatement)expression [NOT] IN (sqlstatement)[NOT] EXISTS (sqlstatement)

    This example lists the name, title, and salary of every sales representative whose salary is higher thanthat of all managers and directors.

  • 8/12/2019 Visual Basic Programming Aan

    51/112

  • 8/12/2019 Visual Basic Programming Aan

    52/112

    VISUAL BASIC

    52

    way would be in one table. You might use a one-to-one relationship to divide a wide table, to isolatepart of a table for security reasons, or to store information that only applies to a subset of the maintable. For example, you might want to create a table to track employees participating in a fundraisingsoccer game.

    A one-to-many relationship is created if only one of the related fields is a primary key or has aunique index.

    A one-to-one relationship is created if both of the related fields are primary keys or have uniqueindexes.

    A many-to-many relationship is really two one-to-many relationships with a third table whoseprimary key consists of two fields the foreign keys from the two other tables.

    Primary keyYou can use the Primary property to specify whether the index is the primary key for the table. Aprimary key uniquely identifies each record in a table and prevents you from entering duplicate valuesin a primary key field.

    Foreign keyForeign key is a column or group of column in a table that corresponds to or references a primary keyin another table in the database. A foreign key need not be unique, but it must uniquely identify the

    column in the table that it references.

    5.6 Querying a Database

    To work with the data in a database, you can use queries to manipulate or extract data. Aquery either asks the database for a set of records matching specified criteria (a SELECT query), ortells the database to perform a specified operation on a set of records that match specified criteria (anaction query).

    You can use a data control's RecordSource property to query the database, or you can use oneof the Find methods with a data control's Recordset property.

    Using an SQL query with a data control

    Design your query so the database returns only the records you want.

    Enter the SQL statement in the RecordSource property. You can do this at design time or runtime. At run time, you can use this code:

    Data1.RecordSource = "SELECT * FROM Employees WHERE Salary >= 10000'"

    At run time, use the Refresh method to recreate the data control, ie rearranging data in thedatabase:

    Data1.Refresh

    In your program you can use variables also

    For example you want to select all the details about a particular employee, you can define a variableand assign employee code to that. You can compare this variable with the following query statement.

    Dim empcode as integer

    Data1.RecordSource = SELECT * FROM Employees WHERE Empid = & empcode

    data1.refresh

    If empid data type is def