Visual Basic

89
Visual Basic 1. INTRODUCTION........................................................ 2. OPTION BUTTONS...................................................... 3. CHECK BOXES......................................................... 4. SCROLLBARS.......................................................... 5. CONTROL STRUCTURES.................................................. 6. MOUSE EVENTS........................................................ 7. KEYBOARD EVENTS..................................................... 8. DIALOG BOXES........................................................ 9. LIST BOX & COMBO BOX................................................ 10. FOCUS.............................................................. 11. TIMER CONTROL...................................................... 12. ARRAYS............................................................. 13. MENUS.............................................................. 14. MICROSOFT ACCESS................................................... 15. DATABASE PROGRAMMING............................................... 16. ACTIVEX CONTROLS................................................... 17. Web Browser........................................................

description

good

Transcript of Visual Basic

Page 1: Visual Basic

Visual Basic

1. INTRODUCTION........................................................................................................................................

2. OPTION BUTTONS....................................................................................................................................

3. CHECK BOXES...........................................................................................................................................

4. SCROLLBARS.............................................................................................................................................

5. CONTROL STRUCTURES........................................................................................................................

6. MOUSE EVENTS........................................................................................................................................

7. KEYBOARD EVENTS................................................................................................................................

8. DIALOG BOXES.........................................................................................................................................

9. LIST BOX & COMBO BOX.......................................................................................................................

10. FOCUS.........................................................................................................................................................

11. TIMER CONTROL...................................................................................................................................

12. ARRAYS.....................................................................................................................................................

13. MENUS........................................................................................................................................................

14. MICROSOFT ACCESS.............................................................................................................................

15. DATABASE PROGRAMMING...............................................................................................................

16. ACTIVEX CONTROLS............................................................................................................................

17. Web Browser...............................................................................................................................................

Page 2: Visual Basic

Visual Basic

1. INTRODUCTIONApplication development Using Visual BasicMicrosoft Visual Basic is a powerful development platform that you can use to create feature-rich applications for the Windows 95 and Windows NT operating systems quickly and easily. Although professional programmers use visual Basic, it is easy for novices to program in Visual Basic with professional result.

Features in Visual BasicVisual Basic provides a rapid application development (or RAD) environment, a rich object-based language, and an easy to use set of debugging tools. For companies developing custom applications, using Visual Basic reduces the development time and costs. Its intuitive interface makes the makes Visual Basic an excellent tool for programmers.New users benefit from mouse operations and a consistent look and feel; more advanced users benefit from ease of use features, such as drop down list boxes and multiple windows applications.Visual Basic supports a number of features that make it an excellent language for quickly creating full-featured solutions, including: Multiple Windows Platforms OLE programmability Rapid Application Development (RAD)

Editions of Visual BasicVisual Basic Version 6.0 is available in 3 editions The Learning Edition: This is the introductory edition, which carries all the tools required to build and

maintain a windows application. Professional Edition: The professional edition is for application developers and includes advanced

features such as tools for developing Active X controls Enterprise Edition: The enterprise edition is the most advanced edition and is aimed at programmers

who build distributed applications in a team environment. It includes all the features of the professional edition, plus the tools such as Visual SourceSafe (a version control system) and the automation and Component Manager, which are not covered in this book.

Visual Basic Terminology Visual Basic requires an understanding of some common terminology. The following table lists some key

terms used in visual Basic. you will learn more about each term later in the course.

Term DefinitionDesign Time Any time an application is being developed in the Visual Basic environment.

Run Time Any time an application is running. At run time, the programmer interacts with the application as the user would.

Forms Windows that serve as the interface for an application or as dialog boxes used to gather information from the user.

Controls Graphical representations of objects, such as buttons, list boxes, and edit boxes that users manipulate to provide information to the application.

Properties The characteristic of an object such as size, Text or color.

Methods The actions that an object can perform or that can be performed on the object.

Events Actions recognized by a form or control. Events occur as the user, operating system, or application interacts with the objects of a program.

Event Driven When a program is event driven, its code executes in response to events invoked by the user, operating system or application.

1

Page 3: Visual Basic

Visual Basic

Types of Applications in Visual Basic 6.0 Standard.Exe: A standard Exe project is a typical application.

Active X EXE, Active X DLL: These types of projects are available with the Professional edition. Active X components are OLE automation servers and there are the basic code-building components that do not have a visual basic interface and that you can add special functionality to your application.

Active X Control: This type of project is also a feature of the professional edition. Use it to develop your own Active X control.

Active X Document EXE, Active X DLL: Active X documents are in essence Visual Basic applications that can run in the environment of a container that supports hyperlinking (such as Internet Explorer).

VB Application Wizard, VB Wizard Manager: The Application Wizard takes you through the steps of setting up the skeleton of a news application. The Wizard Manager lets you build your own Wizard. A wizard is a sequence of windows that collects information from the user and builds an application based on it.

Data Project: This feature is available in the Enterprise edition, and it does not correspond to a new project type. It is identical to the Standard.EXE project type, but it automatically adds the controls that are used in accessing the databases to the toolbox.

DHTML Application: VB6 allows you to build Dynamic HTML pages that can be displayed in the browser's window on a client computer.

IIS Application: VB6 allows you to build application that run on the Web server and interact with clients over the Internet with the Internet Information Server.

Addin: You can create your own add-ins for the Visual Basic IDE.

Visual Basic ProgrammingVisual Basic is an event-driven programming language

Visual Basic Programming

Visual Programming Code ProgrammingPrograms are designed here Events are coded hereusing the tools that come with the Visual Basic Package{Objects are defined here}

The Integrated Development Environment (IDE)The IDE of Visual Basic consists of a variety of elements. The most commonly used are

Menu Bar

Toolbars

Toolbox: On the extreme left of the screen is the Toolbox. Toolbox contains the icons of the controls that you can place on a Form. The default Toolbox is called as the General Toolbox.

Solution Explorer: The window titled ‘Project’ is the Solution Explorer Window, which displays the components of the project organized in folders.

Properties Window: The Properties Window contains the property settings for the selected control. Properties are attributes of an object.

The Form Designer: It is the main window in the middle of the screen where you can design and edit the application’s user interface. The Form Designer displays two windows for each form – the Form itself and the Code window.

2

Page 4: Visual Basic

Visual Basic

THE CONTROLS OF VISUAL BASIC

Pointer Picture box Label

Textbox Frame Button Button

Checkbox Option Button Combo box

List box Horizontal Scrollbar Vertical Scrollbar

Timer Drive List box Directory List box

File List box Draw Shapes Draw Lines

Image Control Data Access Object OLE Container

Naming Conventions for ControlsControl First 3 characters of Name

Form FrmCheck Box ChkCombo Box CmbButton Button BTNDirectory List DirDrive List DrvFile List FilFrame FraHorizontal Scrollbar HsbVertical Scrollbar VsbImage ImgLabel LblList Box LstMenu MnuOption Button OptShape ShpText Box TxtTimer tmr

The Form

The form is the screen area where controls are placed and events are coded to make modules of an application. It has many properties some of which are given below

Name The default name given to the form

3

Page 5: Visual Basic

Visual Basic

Left The x coordinate of the upper left corner of the form.Top The y coordinate of the upper left corner of the formWidth Width specifies the width of the form in pixelsHeight Height specifies the height of the form in pixelsIcon The icon that appears when the form is minimizedMousePointer The shape of the mouse pointer when it runs over the form at execution time.WindowState The state of the form (maximized, minimized or normal) when the form is run.

The Textbox Textboxes are used to enter and display information as String values. They have various properties. Following are some of the commonly used properties.

Name Returns the name used to identify the textbox.Text Sets the text contained in the textbox.Enabled Sets the value that determines whether or not the textbox can respond to user generated

events.Max Length Determines the maximum number of characters allowed in the textbox.Multi Line Allows text to wrap as text is entered into a textbox. When the multi line property is true,

you can use the Alignment property to left, right, or center justify text, and enter more than one line. When the multi line property is set to false, Visual Basic does not allow the user to specify the alignment property.

Scrollbars Enables you to attach built in scrollbars to the textbox so that users can scroll text in the textbox when the program is running. The default value is 0, which signifies no scrollbars. The values 2 and 3 can be used if the multi line property is set to true.

Password Char

Is used for displaying specified characters when the user types a password. Normally, this property is not set – it is empty. For example, if Password Char is set to X, and the user enters a 5-character password then XXXXX will be displayed in the textbox.

BorderStyle The default BorderStyle value is 1, which provides a thin line around the box.

The Label: - Labels are used as tags to describe what kind of information the Textboxes contain. They are normally placed on the left of the Textbox. If the Textbox is displaying an Employee Name, then The Label’s Text property will be set to the String “First Name:” Following are some of the properties of the Label control –

Name Returns the name used to identify the label box.Text Determines the text displayed in the label.Visible Determines whether the label box should be visible or not.Autosize Determines whether Visual Basic should automatically resize the label’s border to fit

the label Text.Alignment The values 0, 1 and 2 indicate left, right and center alignment respectively. By default,

captions are aligned to the left.Border Style Determines whether a visible border appears around the label.

The Button Button:Button Buttons are used to trigger a sequence of action or check for a condition when the mouse is clicked on them. They have properties similar to the ones described for the previous controls. Of special interest are the Visible And Enabled properties which when set to False make the Button invisible and Disabled when the program is run. Disabled means that even if there is a mouse click on the Button then it will be disregarded and no event or action will be triggered.Name Returns the name used to identify the Button button.Text Determines the text to be displayed.Value Returns or sets a value indicating whether the button is chosen or not. The property is not

available at design time.

4

Page 6: Visual Basic

Visual Basic

Program 1 – Hello Program

Form Name FRMHELLOText The Hello ProgramWindowState 2-Maximized

Text 1 Name TXTHELLOTextAlignment 2-CenterBackColor Any Light ColorForeColor Any Dark ColorFont Change if Reqd.ReadOnly True

Button 1 Name BTNDISPLAYText &DISPLAY

Button 2 Name BTNCLEARText &CLEAR

Button 3 Name BTNXText E&XIT

Code:Private Sub BTNCLEAR_Click( )TXTHELLO.Text = " "End Sub

Private Sub BTNDISPLAY_Click( )TXTHELLO.Text = "HELLO"End Sub

Private Sub BTNX_Click( )EndEnd Sub

Some Important Statements Private Sub: When you are writing the code for a particular object, the first line of the code, which

Visual Basic writes for you begins with the words ‘Private Sub’. Sub is a keyword indicating the beginning of a procedure. A procedure is a code dedicated to a particular event. The name of the procedure is ‘Objectname_Event’

End Sub: It is the last line of the procedure and marks the end of the procedure. End: It causes a Visual Basic program to terminate. Dim: It is an instruction to Visual Basic that the following word is the name of a variable.

5

Page 7: Visual Basic

Visual Basic

2. Option ButtonsThe Option Button Option Buttons are controls that are used together within a group. They indicate alternative options to be chosen in response to a particular type of information. They are grouped together within one frame and at any time only one option button can be chosen from a group. Some of the properties are: - Name Assigns a name to identify the option button.Text Specifies the text that appears besides the option button.Alignment Determines the alignment of the option button with respect to the Text.Checked Returns or sets the state of the option button.

The GroupBoxGroupboxes are used to enclose checkboxes and option buttons which are other controls discussed later in this chapter. They indicate a group of controls on the form, which contain related information of one type. Their properties are: -

Name Assigns a name to identify the frame.Text Specifies the Text text.Visible Returns or sets the value indicating whether or not the frame is visible.Enabled Determines whether a control can respond to user – generated events.

Picture ControlThe Image control is similar to the Picture box control except that that it has the special stretch property, which allows the picture to fit and adjust to the size of the contained Bitmap image.

Name The name of the image controlPicture By default, there is no image displayed in the control, but Can be set to the

pathname of a .BMP,.ICO,.JPG file. Then The image will be displayed.Stretch This property, if set to true resizes the Image control to fit the size of the bmp file it

displays.

Public ProceduresA public procedure is accessible to any object on a form. It is written in the General Declaration area of the form. A public procedure can be created using Tools –> Add Procedure (in the code window only)

Program 2 – Option Button Program

Form Name FRMOPTIONText The Option Button Program

6

Page 8: Visual Basic

Visual Basic

WindowState 2-MaximizedText 1 Name TXTOPTION

TextAlignment 2-CenterFont Change if Reqd.ReadOnly TrueText Visual Basic

Option 1 Option 2 Option 3Name OPTRED OPTGREEN OPTBLUEText &RED &GREEN &BLUE

Button 1 Name BTNXText E&XIT

GroupBox 1 Text ForeColor

Option 4 Option 5 Option 6Name OPTR OPTG OPTBText RE&D GREE&N B&LUE

CodePrivate Sub BTNX_Click( )EndEnd Sub

Private Sub OPTBlue_Click( )TXTOPTION.BackColor = Color.BlueEnd Sub

Private Sub OPTB_ Click ( )TXTOPTION.ForeColor = Color.BlueEnd Sub

Private Sub OPTGreen_ Click ( ) TXTOPTION.BackColor = Color.GreenEnd Sub

Private Sub OPTG_ Click ( ) TXTOPTION.ForeColor = Color.GreenEnd Sub

Private Sub OPTRed_ Click ( )TXTOPTION.BackColor = Color.RedEnd Sub

Private Sub OPTR_ Click ( )TXTOPTION.ForeColor = Color.RedEnd Sub

Program 3 – Face Program

Form Name FRMFACEText The Face ProgramWindowState 2-Maximized

Option 1 Option 2 Option 3Name OPTHAPPY OPTOK OPTSADText &HAPPY &OK &SAD

7

Page 9: Visual Basic

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\MiscPicture 1 Picture 2 Picture 3

Name PCTHAPPY PCTOK PCTSADPicture Face02 Face01 Face04Visible False False False

Label 1 Label 2 Label 3Name LBLHAPPY LBLOK LBLSADText I am Happy I am Ok I am SadBorderStyle 1-FixedSingle 1-FixedSingle 1-FixedSingleVisible False False False

Button 1 Name BTNXText E&XIT

CodePublic Sub Face( )If OPTHAPPY.Checked = True Then PCTHAPPY.Visible = True LBLHAPPY.Visible = True Else PCTHAPPY.Visible = False LBLHAPPY.Visible = False End IfIf OPTOK.Checked = True Then PCTOK.Visible = True LBLOK.Visible = True Else PCTOK.Visible = False LBLOK.Visible = False End IfIf OPTSAD.Checked = True Then PCTSAD.Visible = True LBLSAD.Visible = True Else PCTSAD.Visible = False LBLSAD.Visible = False End If

End Sub

Private Sub BTNX_Click( )EndEnd Sub

Private Sub OPTHAPPY_Click( )FACE ( )End Sub

Private Sub OPTOK_ Click ( )FACE ( )End Sub

Private Sub OPTSAD_ Click ( )FACE ( )End Sub

7

Page 10: Visual Basic

3. Check BoxesThe Check Box: The Checkbox is a control that asks the user for Yes-No type of information. Some of the properties are: - Name Assigns a name to identify the checkboxText Specifies the text that appears besides the checkboxEnabled Sets a value that determines whether the checkbox can respond to user generated

eventsChecked Is used to specify the state of a checkbox. If the value is false, the checkbox is

deselected. If the value is true, the checkbox is selected.

Program 4 – Flag Program

Form Name FRMFLAGText The Flag ProgramWindowState 2-Maximized

Check 1 Check 2 Check 3Name CHKAUS CHKUSA CHKUKText &AUSTRALIA &USA U&K

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\FlagsPicture 1 Picture 2 Picture 3

Name PCTAUS PCTUSA PCTUKPicture Flgastrl Flgusa02 FlgukVisible False False False

Button 1 Name BTNXText E&XIT

CodePrivate Sub CHKAUS_ Click ( )If CHKAUS.Checked = True Then PCTAUS.Visible = TrueElse PCTAUS.Visible = FalseEnd IfEnd Sub

Private Sub CHKUSA_ Click ( )If CHKUSA.Checked = True Then PCTUSA.Visible = TrueElse PCTUSA.Visible = FalseEnd IfEnd Sub

Private Sub CHKUK_ Click ( )If CHKUK.Checked = True Then PCTUK.Visible = TrueElse PCTUK.Visible = FalseEnd IfEnd Sub

Private Sub BTNX_Click( )EndEnd Sub

8

Page 11: Visual Basic

Program 5 – Check Box Program

Form Name FRMCHECKText The Check Box ProgramWindowState 2-Maximized

Check 1 Check 2 Check 3Name CHKRED CHKGREEN CHKBLUEText &RED &GREEN &BLUE

Label 1 Name LBLCHECKText -BorderStyle 1-FixedSingle

Button 1 Name BTNXText E&XIT

CodePrivate Sub CHKBlue_ Click ( )CHECK ( )End Sub

Private Sub CHKGreen_ Click ( )CHECK ( )End Sub

Private Sub CHKRed_ Click ( )CHECK ( )

End Sub

Private Sub BTNX_Click( )EndEnd Sub

Private Sub Form_Load( )CHECK ( )End Sub

Public Sub CHECK( )Dim INFO If CHKRed.Checked = True Then INFO = "YOU HAVE SELECTED THE RED CHECK BOX"Else INFO = "YOU HAVE DESELECTED THE RED CHECK BOX"End IfIf CHKBlue.Checked = True Then INFO = INFO + Chr(13) + "YOU HAVE SELECTED THE BLUE CHECK BOX"Else INFO = INFO + Chr(13) + "YOU HAVE DESLECTED THE BLUE CHECK BOX"End IfIf CHKGreen.Checked = True Then INFO = INFO + Chr(13) + "YOU HAVE SELECTED THE GREEN CHECK BOX"Else INFO = INFO + Chr(13) + "YOU HAVE DESELECTED THE GREEN CHECK BOX"End IfLBLCHECK.Text = INFOEnd Sub

9

Page 12: Visual Basic

Assignment

The label should display the status of each check box – ON or OFF and the selected level.

10

Page 13: Visual Basic

4. ScrollbarsScrollbarsScrollbar is a commonly used control in Windows programs. The object enables the user to select a value by positioning the thumb (the square tab on the scrollbar) to a desired position. A scrollbar represents a set of positive integer values. To cover a range of negative values or decimal numbers you must use a little Maths in your code. For e.g., to set the range from 2.5 to 8.5, set the Min and Max properties to 25 and 85 respectively and divide the control’s value by 10. If the range you need is -2.5 to 8.5 set the Min and Max properties to 0 to 110 (25 + 85) respectively. To get the required value, divide the control’s value by 10 and subtract 2.5 from it.

The Horizontal ScrollbarThe Horizontal Scrollbar is used to scroll up and down a list of items in a list box , a file list box, a drive list box, and a directory list box. It is provided with a thumb, which moves to and from the extreme left and right of the scrollbar. You can set the following properties

Name Represents the name of the scroll barMin The value the scroll bar has when the thumb is at the extreme left.Max The value when the thumb is on the extreme rightValue The current value of the thumb

The Vertical Scrollbar The Vertical Scrollbar is similar to the horizontal scrollbar except that it is vertically aligned to the form. The movement of the thumb is upward and downward instead of to the right and left. The Vertical Scrollbar also has a Min, Max and Value property which can be set and changed to monitor the movement of the thumb.

Name Represents the name of the scroll barMin The value the scroll bar has when the thumb is at the extreme left.Max The value when the thumb is on the extreme rightValue The current value of the thumb

The Scrollbar Control EventsThe user can change the scrollbar’s value in 3 ways: By clicking the arrows at the end. The value changes by the amount specified with the SmallChange

property. By clicking the area between the indicator and the arrows. The value changes by the amount specified

with the LargeChange property. By scrolling the indicator with the mouse.

You can monitor the changes on the scrollbar’s value from within your code with two events: Change Event: The change event occurs every time the user changes the indicator’s position and

releases the mouse button. For e.g., if the user clicks on the indicator and holds down the mouse button while moving the indicator, no change event is triggered. The change event occurs only when the mouse button is released.

Scroll Event: The scroll event occurs continuously while the indicator is moving. After the mouse button is releases, the control stops triggering the scroll event and triggers a single change event.

Specifying Colors with RGB() FunctionThe FromArgb() function enables you to specify colors. The letters RGB stand for Red, Green and Blue. All colors that can be displayed are generated by mixing these 3 primary colors. The FromArgb() function has 3 parameters; representing amount of red, green and blue in the final color. The minimum value of each parameter in the FromArgb() function is 0 and the maximum value is 255.

Program 6 – Multiplication Program

11

Page 14: Visual Basic

Form Name FRMMULTIPLYText The Multiplication ProgramWindowState 2-Maximized

Label 1 Label 2 Label 3 Label 4Name LBLVSB LBLHSB Label1 LBLRESULTText - - Result: -BorderStyle 1-FixedSingle 1-FixedSingle 1-FixedSingle 1-FixedSingle

HScroll 1 Name HSBNUMMin 1Max 100

VScroll 1 Name VSBNUMMin 1Max 100

Button 1 Button 2Name BTNMULTIPLY BTNXText &MULTIPLY E&XIT

CodePrivate Sub BTNMULTIPLY_Click( )LBLRESULT.Text = HSBNUM.Value * VSBNUM.ValueEnd Sub

Private Sub BTNX_Click( )EndEnd SubPrivate Sub Form_Load( )LBLVSB.Text = VSBNUM.ValueLBLHSB.Text = HSBNUM.ValueEnd Sub

Private Sub HSBNUM_Scroll( )LBLHSB.Text = HSBNUM.ValueEnd Sub

Private Sub VSBNUM_Scroll( )LBLVSB.Text = VSBNUM.ValueEnd Sub

12

Page 15: Visual Basic

Program 7 – The Scrollbar Program

Form Name FRMSCROLLText The Scroll Bar ProgramWindowState 2-Maximized

Label 1 Name LBLSCROLLText -BorderStyle 1-FixedSingle

HScroll 1 Name HSBNUMMin 1Max 100

VScroll 1 Name VSBNUMMin 1Max 100

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click( )EndEnd SubPrivate Sub Form_Load( )SCROLLEnd Sub

Private Sub HSBNUM_Scroll( )VSBNUM.Value = HSBNUM.ValueSCROLLEnd Sub

Private Sub VSBNUM_Scroll( )HSBNUM.Value = VSBNUM.ValueSCROLLEnd Sub

Public Sub SCROLL( )LBLSCROLL.Text = "VALUE OF VSB : " & Str(VSBNUM.Value) & Chr(13) & _

"VALUE OF HSB : " & Str(HSBNUM.Value)End Sub

13

Page 16: Visual Basic

Program 8 – The RGB () Function

Form Name FRMRGBText The RGB() FunctionWindowState 2-Maximized

Label 1 Label 2 Label 3Text Red Green Blue

HScroll 1 HScroll 2 HScroll 3Name HSBRED HSBGREEN HSBBLUEMin 0 0 0Max 255 255 255

Label 4 Label 5 Label 6Name LBLHSBR LBLHSBG LBLHSBBText - - -BorderStyle 1-FixedSingle 1-FixedSingle 1-FixedSingle

Label 7 Label 8 Label 9Text Red Green Blue

Trackbar 1 Trackbar 2 Trackbar 3Name TRKRED TRKGREEN TRKBLUEMin 0 0 0Max 255 255 255

Label 10 Label 11 Label 12Name LBLTRKR LBLTRKG LBLTRKBText - - -BorderStyle 1-FixedSingle 1-FixedSingle 1-FixedSingle

Label 13 Label 14 Label 15Text Red Green Blue

NumericUpDown 1 NumericUpDown 2 NumericUpDown 3 Name UDRED UDGREEN UDBLUEMin 0 0 0Max 255 255 255

14

Page 17: Visual Basic

Text 1 Text 2 Text 3Name TXTSCROLL TXTTRACK TXTUPDOWNText - - -ReadOnly True True True

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click( )EndEnd Sub

Private Sub Form_Load( )SCROLLSLIDERUDEnd Sub

Public Sub SCROLL( )LBLHSBR.Text = HSBRed.ValueLBLHSBG.Text = HSBGreen.ValueLBLHSBB.Text = HSBBlue.ValueTXTSCROLL.BackColor = Color.FromArgb(255, HSBRed.Value, HSBGreen.Value, HSBBlue.Value)End Sub

Public Sub TRACK( )LBLTRKR.Text = TRKRED.ValueLBLTRKG.Text = TRKGREEN.ValueLBLTRKB.Text = TRKBLUE.ValueTXTTRACK.BackColor = Color.FromArgb(255, TRKRed.Value, TRKGreen.Value, TRKBlue.Value)End Sub

Private Sub HSBBlue_Scroll( )SCROLLEnd Sub

Private Sub HSBGreen_Scroll( )SCROLLEnd Sub

Private Sub HSBRed_Scroll( )SCROLLEnd Sub

Private Sub TRKBlue_Scroll( )TRACKEnd Sub

Private Sub TRKGreen_Scroll( )TRACKEnd Sub

Private Sub TRKRed_Scroll( )TRACKEnd Sub

Private Sub UDBlue_Change( )UDEnd Sub

Private Sub UDGreen_Change( )UDEnd Sub

Private Sub UDRed_Change( )UDEnd Sub

Public Sub UD( )TXTUPDOWN.BackColor = Color.FromArgb(255, UDRed.Value, UDGreen.Value, UDBlue.Value)End Sub

15

Page 18: Visual Basic

5. Control StructuresDECISION MAKING STATEMENTS If – Then – Else – End If

If <condition> Then<statementblock>

End If

If <condition1> Then<statementblock1>

Else<statementblock2>

End If

If – Then – ElseIf – End IfIf <condition1> Then

<statementblock1>ElseIf <condition2> Then

<statementblock2>ElseIf <condition3> Then

<statementblock3>Else

<statementblock4>End If

The If – End If structure tests the condition specified, and executes the statements that follow, if the condition is True.

Select Case – End SelectSelect Case <expression>

Case <value1><statementblock1>

Case <value2><statementblock2>

Case <value3><statementblock3>

Case Else<statementblock4>

End Select

The Select Case – End Select structure tests a single expression, which is evaluated once at the top of the structure. The result of the test is then compared with several values, and if it matches one of them, the corresponding statements are executed.

LOOP STRUCTURES Do While – Loop

Do while <condition><statementblock>

Loop

The Do While – Loop executes a block of statements as long as the specified condition is true.

While – WendWhile <condition>

<statementblock>End While

16

Page 19: Visual Basic

Do – Loop WhileDo

<statementblock>Loop While <condition>

The statements in this type of loop are executed atleast once, since the condition is executed at the end of the loop. Then the statements are executed depending upon the specified condition.

For – NextFor <variable> = <start value> To <end value> <step value>

<statementblock>Next

Note: If you accidentally enter an indefinite loop, press Ctrl + Break to exit.

With – End WithWith <objectname>

<properties>End With

The With – End With structure enables you to set several properties of an object without typing the name of the object for each property.

CommentsComments in Visual Basic are written either by adding a single quote (‘) or writing the word REM before the line.

Option ExplicitThis statement tells the compiler to check each variable before using it and to issue an error message if you attempt to use a variable without declaring it. If you omit the Option Explicit statement, Visual Basic creates variables as needed.

Tab OrderAll windows applications allow the user to move the focus from one control to another with the Tab key. The order in which the focus moves from one control to another, each time the user presses the tab key is called as Tab Order. You can use the TabIndex property to change the Tab Order.

If you don’t want the user to move to a specific control, you can remove it from the Tab Order by setting its TabStop property to False.

The members of an option button group have a single TabStop, as only one button can be selected from the group. Within a group, you can use the arrow keys to select to the next / previous button and deselect the currently selected button.

Program 9 – Control Structures

17

Page 20: Visual Basic

Form Name FRMSTRUCTUREText Programming StructuresWindowState 2-Maximized

Button 1 Button 2 Button 3Name BTNS1 BTNS2 BTNS3Text STRUCTURE&1 STRUCTURE&2 STRUCTURE&3

Button 4 Button 5 Button 6Name BTNS4 BTNS5 BTNS6Text STRUCTURE&4 STRUCTURE&5 STRUCTURE&6

Button 7 Button 8 Button 9Name BTNS7 BTNS8 BTNS9Text STRUCTURE&7 STRUCTURE&8 STRUCTURE&9

Button 10 Button 11Name BTNS10 BTNXText STRUCTURE1&0 E&XIT`

Label1 Name LBLSTRUCText -

CodeOption Explicit

Private Sub BTNS9_Click( )LBLSTRUC.Text = “”Dim MM = 0While M < 1 Or M > 12 M = InputBox("ENTER A NUMBER")End While LBLSTRUC.Text "YOU HAVE CHOSEN THE MONTH: " & Choose(M, "JANUARY", _ "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", _ "OCTOBER", "NOVEMBER", "DECEMBER")End Sub

Private Sub BTNS10_Click( )LBLSTRUC.Text = “”Dim NAMEARRAY(6)NAMEARRAY(0) = "A"NAMEARRAY(1) = "R"NAMEARRAY(2) = "C"NAMEARRAY(3) = "H"NAMEARRAY(4) = "A"NAMEARRAY(5) = "N"NAMEARRAY(6) = "A"Dim CTR, NONO = 1For Each CTR In NAMEARRAY LBLSTRUC.Text = LBLSTRUC.Text & Chr (13) & "Character " + Str(NO) & " of your name is " & CTR NO = NO + 1NextEnd Sub

18

Page 21: Visual Basic

Private Sub BTNS1_Click( )LBLSTRUC.Text = “”Dim II = 1Do While I <= 25 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & I I = I + 1LoopEnd Sub

Private Sub BTNS2_Click( )LBLSTRUC.Text = “”Dim II = 50Do LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & ILoop While I <= 25End Sub

Private Sub BTNS3_Click( )LBLSTRUC.Text = “”Dim IFor I = 1 To 50 Step 2 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & INextEnd Sub

Private Sub BTNS4_Click( )LBLSTRUC.Text = “”Dim IFor I = 1 To 50 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & I If I = 25 Then Exit For End IfNextEnd Sub

Private Sub BTNS5_Click( )LBLSTRUC.Text = “”Dim II = 1Do While I <= 50 I = I + 1 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & I If I = 30 Then Exit Do End IfLoopEnd Sub

Private Sub BTNS6_Click( )LBLSTRUC.Text = “”Dim II = 1Do While I <= 50 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & I I = I + 1 If I = 30 Then Exit Do End IfLoopEnd Sub

Private Sub BTNS7_Click( )LBLSTRUC.Text = “”Dim II = 1While I <= 20 LBLSTRUC.Text = LBLSTRUC.Text & _ Chr (13) & I I = I + 1End WhileEnd Sub

Private Sub BTNS8_Click( )Dim INTVALUE, INTABSVALUEINTVALUE = InputBox("ENTER A NUMBER")If Not IsNumeric(INTVALUE) Then MsgBox "NOT A VALID NUMBER" Exit SubElse INTABSVALUE = IIF(INTVALUE < 0, -1 *

INTVALUE, INTVALUE) LBLSTRUC.Text = "ABSOLUTE VALUE =

" & Str(INTABSVALUE)End IfEnd Sub

Private Sub BTNX_Click( )EndEnd Sub

19

Page 22: Visual Basic

Assignment

The value of the scrollbar should be displayed in the label below it. When you click on the SUM IT button, the RESULT label should display the result as 1 + 2 + 3 + … + scrollbar value.

20

Page 23: Visual Basic

6. Mouse EventsClient AreaThe unutilized area enclosed by the Title bar of the form and the edges of the form window is called as the client area.

QBColor() FunctionThe QBColor() function is used to specify colors. It has only one parameter that takes any integer value from 0 – 15. i.e., it generates 16 colors. Following is the QBColor () Chart

Value Color Value Color0 Black 8 Gray1 Blue 9 Light Blue2 Green 10 Light Green3 Cyan 11 Light Cyan4 Red 12 Light Red5 Magenta 13 Light Magenta6 Yellow 14 Light Yellow7 White 15 Bright White

Program 10 – The Mouse Events Program

Form Name FRMMOUSEText The Mouse Events ProgramWindowState 2-Maximized

Label 1 Name LBLMOUSEText -BorderStyle 1-FixedSingle

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click( )EndEnd Sub

Private Sub Form_MouseDown( )If e.Button = Windows.Forms.MouseButtons.Left Then LBLMOUSE.Text = "YOU HAVE PRESSED THE LEFT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Right Then LBLMOUSE.Text = "YOU HAVE PRESSED THE RIGHT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Middle Then LBLMOUSE.Text = "YOU HAVE PRESSED THE MIDDLE BUTTON"End IfEnd Sub

21

Page 24: Visual Basic

Private Sub Form_MouseMove( )If e.Button = Windows.Forms.MouseButtons.Left Then LBLMOUSE.Text = "YOU ARE MOVING THE LEFT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Right Then LBLMOUSE.Text = "YOU ARE MOVING THE RIGHT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Middle Then LBLMOUSE.Text = "YOU ARE MOVING THE MIDDLE BUTTON"End IfEnd Sub

Private Sub Form_MouseUp( )If e.Button = Windows.Forms.MouseButtons.Left Then LBLMOUSE.Text = "YOU HAVE RELEASED THE LEFT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Right Then LBLMOUSE.Text = "YOU HAVE RELEASED THE RIGHT BUTTON"End IfIf e.Button = Windows.Forms.MouseButtons.Middle Then LBLMOUSE.Text = "YOU HAVE RELEASED THE MIDDLE BUTTON"End IfEnd Sub

7. Keyboard Events

KeyDown: The KeyDown event occurs when you press any of the keys on the keyboard.

22

Page 25: Visual Basic

KeyUp: The KeyUp event occurs when you release the pressed key. KeyPress: The KeyPress event occurs when you press a key that has a corresponding Ascii character.

For e.g., if you press the function key F1, the KeyPress event does not occur, but if you press the A key, the KeyPress event takes place.

Parameters of Keyboard EventsThe KeyDown and KeyUp events have 2 parameters:

KeyCode: It is an integer that represents the pressed / released key. Shift: This parameter represents the state of Shift key.

The KeyPress Event has only one parameter

KeyChar: It represents the character value of the pressed key.

Chr() FunctionThe Chr() function converts the integer KeyAscii to a character value.

Asc() FunctionThe Asc() function returns an integer that represents the Ascii value of the pressed key.

KeyPreview PropertyA form can have the keyboard focus if there are no controls on it or if the controls are disabled. However in most programs, a form does have some enabled controls on it, so the Form_KeyDown, Form_KepUp and Form_KeyPress procedures are not executed.

To force the execution of these procedures, even when the form does not have the keyboard focus, set the KeyPreview property of the form to True. The KeyPreview property enables the program to trap or preview the keyboard events.

Program 11– The Keyboard Events

Form Name FRMKEYText The Keyboard EventsWindowState 2-MaximizedKeyPreview True

Label 1 Label 2Name LBLKEY LBLASCIIText - -BorderStyle 1-FixedSingle 1-FixedSingle

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click( )EndEnd Sub

23

Page 26: Visual Basic

Private Sub Form_KeyDown( )LBLKEY.Text = "THE KAY HAS BEEN PRESSED" + Chr(13) + _

"KEYCODE =" + Str(e.KeyCode) + Chr(13) + "SHIFT:" + Str(e.Shift)End Sub

Private Sub Form_KeyPress( )Dim C As StringC = e.KeyCharLBLASCII.Text = "THE KEY HAS BEEN PRESSED" & Chr(13) & _

"ASCII VALUE=" & Asc(C) & Chr(13) & "CHARACTER=" & CEnd Sub

Private Sub Form_KeyUp( )LBLKEY.Text = "THE KAY HAS BEEN RELEASED" + Chr(13) + _

"KEYCODE =" + Str(e.KeyCode) + Chr(13) + "SHIFT:" + Str(e.Shift)End Sub

Program 12 – The Caps Lock Program

Form Name FRMCAPSText The CapsLock ProgramWindowState 2-Maximized

Text 1 Name TXTCAPSText -MultiLine True

Button 3 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click()EndEnd Sub

Private Sub TXTCAPS_KeyPress(KeyAscii As Integer)Dim C AS StringC = e.KeyChare.KeyChar = UCase(C)End Sub

Program 13 – The Validation Program

24

Page 27: Visual Basic

Form Name FRMVALIDText The Validation ProgramWindowState 2-Maximized

Label 1 Label 2 Label 3Text Enter Only Enter Only Lower Enter Only Upper

Numbers Case Characters Case CharactersAutoSize True True True

Text 1 Text 2 Text 2Name TXTNUM TXTLCASE TXTUCASEText - - -

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click()EndEnd Sub

Private Sub TXTLCASE_KeyPress(KeyAscii As Integer)If Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then e.KeyChar = Chr(0)End IfEnd Sub

Private Sub TXTNUM_KeyPress(KeyAscii As Integer)If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 56 Then e.KeyChar = Chr(0)End IfEnd Sub

Private Sub TXTUCASE_KeyPress(KeyAscii As Integer)If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 90 Then e.KeyChar = Chr(0)End IfEnd Sub

25

Page 28: Visual Basic

8. Dialog Boxes

Dialog boxes are used to display and accept information from the user.

There are 3 types of dialog boxes

Pre-defined Custom Common

MsgBox InputBox

Pre-defined Dialog BoxesAs the name implies, pre-defined dialog boxes are pre-defined by Visual Basic. To display a pre-defined dialog box, you have to use Visual Basic statements with parameters that specify how and when the dialog box should appear. You can display a pre-defined dialog box using:

MsgBoxIt takes 3 parameters – the message to be displayed, the buttons / icons to be displayed and the title for the dialog box, respectively.

It can be used in two ways

Statement Function{It is used to display {It is used for accepting some messages only} information from the user and

storing it in a variable for further processing}Button Constants for MsgBox

Button Constant Value Displayed ButtonvbOKOnly 0 OKvbOKCancel 1 OK, CancelvbAbortRetryIgnore 2 Abort, Retry, IgnorevbYesNoCancel 3 Yes, No, CancelvbYesNo 4 Yes, NovbRetryCancel 5 Retry, Cancel

Button Constants for MsgBoxIcon Constant Value Displayed Icon

vbCritical 16vbQuestion 32vbExclamation 48vbInformation 64

Possible Return Values from the MsgBox() FunctionButton Constant Value Clicked Button

vbOK 1 OKvbCancel 2 CancelvbAbort 3 AbortvbRetry 4 RetryvbIgnore 5 IgnorevbYes 6 YesvbNo 7 No

26

Page 29: Visual Basic

InputBox() Function

InputBox() function can be used to accept information from the user. The InputBox() function displays a dialog box with a message, a text box and buttons for OK and Cancel. The user has to type the information in the text box. The first parameter is the message of the dialog box and the second parameter is the title of the dialog box. You can also use some optional parameters with the InputBox() function. The third parameter specifies the default string that appears in the text box of the dialog box. The fourth and fifth parameters specify the X and Y co-ordinates at which the dialog box should be displayed.

Custom Dialog BoxesCustom dialog boxes are customized / designed by the user as opposed to pre-defined dialog boxes that only let you customize limited things like buttons and icons in the dialog box. Designing a custom dialog box is the same as designing a form. In fact, a custom dialog box is a regular form used to display and accept information from the user.

Cancel and Default Properties

Setting the Cancel property of a Button button to True, makes this button the default cancel button, i.e., the button which is considered to be clicked when the user presses the Esc key.

Setting the Default property of a Button button to True, makes this button the default button, i.e., the button which is considered to be clicked when the user presses the Enter key.

Tag Property

Tag property is used to store the information passed back from a form.

Common Dialog BoxesAll Windows application use some standard dialog boxes for common operations such as selecting a font or opening a file. These dialog boxes are built in the operating system and any application can use them. The Microsoft Common Windows Dialog Controls provides the following built-in Windows dialog boxes.

Method Value Dialog BoxShowOpen 1 OpenShowSave 2 SaveShowColor 3 ColorShowFont 4 FontShowPrinter 5 PrintShowHelp 6 Help

CancelError Property

Each dialog box has a Cancel button, which should notify the application the user’s intention to cancel the current operation. The cancel action can be reported by means of an error. To specify whether an error is generated when the user clicks the Cancel button, set the CancelError property of the common dialog control to True.

If you set the CancelError property to True, you must also provide an error handler, that will detect this condition and act accordingly.

Format() FunctionDate – Stores current dateTime – Stores current timeNow – Stores current date and time

27

Page 30: Visual Basic

Date and Time Format Strings

String Descriptiond The one or two-digit daydd The two-digit day. Single digit day values will be preceded by a zeroddd The three character day-of-week abbreviationdddd The full day-of-week nameh The one or two-digit hour in 12-hour formathh The two-digit hour in 12-hour format. Single digit values will be preceded by a zeroH The one or two-digit hour in 24-hour formatHH The two-digit hour in 24-hour format. Single digit values will be preceded by a zerom The one or two-digit minutemm The two-digit minute. Single digit values will be preceded by a zeroM The one or two-digit month numberMM The two-digit month number. Single digit values will be preceded by a zeroMMM The three character month abbreviationMMMM The full month names The one or two-digit secondss The two-digit seconds. Single digit values will be preceded by a zeroAM/PM The two-letter AM/PM abbreviation y The one-digit year (i.e., 1999 will be displayed as 9)yy The last two digits of the year (i.e., 1999 will be displayed as 99)yyyy The full year

Program 14 – The MsgBox Program

Form Name FRMMSGText The Message Box ProgramWindowState 2-Maximized

Button 1 Button 2Name BTNMSG BTNXText &MESSAGE E&XIT

CodePrivate Sub BTNMSG_Click()Dim MSG As StringDim BTN As IntegerDim TIT As StringMSG = "THIS IS A TRIAL MESSAGE"BTN = vbExclamation + vbOKOnlyTIT = "TRY"MsgBox MSG, BTN, TITEnd Sub

Private Sub BTNX_Click()Dim MSG As StringDim BTN As IntegerDim ANS As IntegerDim TIT As StringMSG = "Are you sure you want to quit?"TIT = "EXIT"BTN = vbYesNo + vbQuestionANS = MsgBox(MSG, BTN, TIT)If ANS = vbYes Then EndEnd IfEnd Sub

28

Page 31: Visual Basic

Program 15 – The InputBox () Program

Form Name FRMINPUTText The Input Box ProgramWindowState 2-Maximized

Button 1 Button 2 Button 3 Button 4Name BTNNAME BTNAGE BTNDOB BTNXText &NAME &AGE &DATE OF BIRTH E&XIT

CodePrivate Sub BTNAGE_Click()Dim AGEAGE = InputBox("ENTER YOUR AGE:", "AGE INPUTBOX")If AGE = "" Then MsgBox "PLEASE ENTER YOUR AGE" Exit SubEnd IfIf Not IsNumeric(AGE) Then MsgBox "PLEASE ENTER ONLY DIGITS" Exit SubEnd IfMsgBox "YOUR AGE IS " + Str(AGE)End Sub

Private Sub BTNDOB_Click()Dim DT As DateDim MSG, DOFWDT = InputBox("ENTERYOUR DOB:", "DOB INPUTBOX")If Not IsDate(DT) Then MsgBox "INVALID DATE" Exit SubEnd IfDOFW = Format(DT, "dddd")MSG = "YOUR DOB IS:" + DT + Chr(13) + Chr(10) + "DAY OF THE WEEK:" + DOFWMsgBox MSG, vbInformation + vbOKOnly, "DATE CONFIRMATION"End Sub

Private Sub BTNNAME_Click()Dim NAMENAME = InputBox("ENTER YOUR NAME:", "NAME INPUTBOX")If NAME = "" Then MsgBox "PLEASE ENTER YOUR NAME"Else MsgBox "HELLO " + NAME End IfEnd Sub

Program 16 – The Custom Dialog Box Program

29

Page 32: Visual Basic

Form Name FRMCUSTOMText The Custom Dialog Box ProgramWindowState 2-Maximized

Button 1 Button 2Name BTNCOUNTRY BTNXText &SELECT COUNTRY E&XIT

Form Name FRMCOUNTRYText Select the CountryControl Box False

Option 1 Option 2 Option3 Option4 Option5Name OPTAUS OPTSWIT OPTCAN OPTMAU OPTUKText &AUSTRALIA &SWITZERLAND &CANADA &MAURITIUS &UK

Button 1 Button 2Name BTNOK BTNCANCELText &OK &CANCEL

CodePrivate Sub BTNCOUNTRY_Click()FRMCOUNTRY.ShowDialog ( )If FRMCOUNTRY.Tag = "" Then MsgBox "OH!SO YOU DON'T WANT TO GO FOR A VACATION"Else MsgBox "ENJOY YOUR VACATION TO " + FRMCOUNTRY.TagEnd IfEnd Sub

Private Sub BTNX_Click()EndEnd Sub

Private Sub BTNCANCEL_Click()Me.Tag = ""Me.HideEnd Sub

Private Sub BTNOK_Click()If OPTAUS.Checked = True Then Me.Tag = "AUSTRALIA"If OPTSWIT.Checked = True Then Me.Tag = "SWITZERLAND"If OPTCAN.Checked = True Then Me.Tag = "CANADA"If OPTMAU.Checked = True Then Me.Tag = "MAURITIUS"If OPTUK.Checked = True Then Me.Tag = "UK"Me.HideEnd Sub

30

Page 33: Visual Basic

9. List Box & Combo Box

The List Box The List box is similar to the combo but differs in the sense that the user cannot edit any value displayed , nor can he manually add an item to the list of strings at runtime . Some of the common properties are

Name The name used to identify the list boxList The user can enter a list of items at design time.

The Combo Box The Combo is a combination of a textbox and a list box. You can enter text in the combo as well as display a list of strings from which a particular item can be selected. Some of the common properties are

Name The name of the Combo BoxText The text displayed in the edit area of the Combo BoxEditable Indicates that the user can edit or changer the values displayed in the combo.List The user can enter a list of items at design time itself

Program 17 – The List Box Program

Form Name FRMLISTText The List Box ProgramWindowState 2-Maximized

Label 1 Label 2Text Enter a Name List of Names

Text 1 Name TXTNAMEText -

List 1 Name LSTNAMES

Button 1 Button 2 Button 3 Button 4Name BTNADD BTNREMOVE BTNCLEAR BTNCOUNTText &ADD &REMOVE &CLEAR C&OUNT

Button 5 Name BTNXText E&XIT

31

Page 34: Visual Basic

CodePrivate Sub BTNADD_Click()If TXTNAME.Text = "" Then MsgBox "Please enter a name" TXTNAME.SetFocus Exit SubEnd IfLSTNAMES.Items.Add (TXTNAME.Text)BTNCLEAR.Enabled = TrueBTNREMOVE.Enabled = TrueTXTNAME.Text = ""TXTNAME.Focus ( )End Sub

Private Sub BTNCOUNT_Click()MsgBox " Total no. of names in the list:" + Str(LSTNAME.Items.Count)End Sub

Private Sub BTNCLEAR_Click()LSTNAMES.Items.Clear( )BTNREMOVE.Enabled = FalseBTNCLEAR.Enabled = FalseEnd Sub

Private Sub BTNREMOVE_Click()If LSTNAMES.SelectedItem = “” Then MsgBox "PLEASE SELECT THE NAME TO REMOVE" Exit SubEnd IfLSTNAME.Items.Remove (LSTNAMES.SelectedItem)If LSTNAMES.Items.Count = 0 Then BTNREMOVE.Enabled = False BTNCLEAR.Enabled = False End IfTXTNAME.Text = ""End Sub

Private Sub BTNX_Click()EndEnd Sub

Private Sub Form_Load()FRMLIST.WindowState = 2BTNREM.Enabled = FalseBTNCL.Enabled = FalseEnd Sub

Private Sub LSTNAMES_SelectedIndexChanged()TXTNAME.Text = LSTNAMES.SelectedItemEnd Sub

32

Page 35: Visual Basic

Program 18 – The Double List Program

Form Name FRMDLText The List Box ProgramWindowState 2-Maximized

List 1 List 2Name LST1 LST2Items A, B, C, D, E 1, 2, 3, 4, 5

Button 1 Name BTNXText E&XIT

CodePrivate Sub BTNX_Click()EndEnd Sub

Private Sub LST1_DoubleClick()LST2.Items.Add (LST1.SelectedItem)LST1..Items.Remove (LST1. SelectedItem)End Sub

Private Sub LST2_DoubleClick()LST1.Items.Add (LST2.SelectedItem)LST2..Items.Remove (LST2. SelectedItem)End Sub

Program 19 – The Combo Box Program

Form Name FRMCOMBOText The Combo Box ProgramWindowState 2-Maximized

Text 1 Name TXTCOMBOTextAlignment 2-CenterFont Change if Reqd.ReadOnly TrueText Visual Basic

Label 1 Label 2Text ForeColor BackColor

Combo 1 Combo 2

33

Page 36: Visual Basic

Name CMBFC CMBBCItems Any 5 colors Any 5 colors

Button 1 Name BTNXText E&XIT

CodePrivate Sub CMBBC_SelectedIndexChanged()Select Case CMBBC.Text Case "WHITE" TXTCOMBO.BackColor = Color.White Case "BLACK" TXTCOMBO.BackColor = Color.Black Case "RED" TXTCOMBO.BackColor = Color.bRed Case "GREEN" TXTCOMBO.BackColor = Color.Green Case "BLUE" TXTCOMBO.BackColor = Color.Blue Case "CYAN" TXTCOMBO.BackColor = Color.CyanEnd SelectEnd Sub

Private Sub CMBFC_Click()Select Case CMBFC.Text Case "WHITE" TXTCOMBO.ForeColor = Color.White Case "BLACK" TXTCOMBO.ForeColor = Color.Black Case "RED" TXTCOMBO.ForeColor = Color.Red Case "GREEN" TXTCOMBO.ForeColor = Color.Green Case "BLUE" TXTCOMBO.ForeColor = Color.Blue Case "CYAN" TXTCOMBO.ForeColor = Color.CyanEnd SelectEnd Sub

Private Sub BTNX_Click()EndEnd SubPrivate Sub Form_Load()

CMBFC.SelectedIndex = 0CMBBC. SelectedIndex = OEnd Sub

34

Page 37: Visual Basic

End Sub

10. Focus

FOCUS

The 3 types of focus are

GotFocus: i.e., when the focus moves to the object. LostFocus: i.e., when the focus moves away from the object. SetFocus: i.e., the focus should move to the object.

Program 20 – The Focus Program

Form Name FRMFOCUSText The Focus ProgramWindowState 2-Maximized

Text 1 Name TXTFOCUSText -

Label 1 Label 2Name Do not change LBLFOCUSText FOCUS -BorderStyle Do not change 1-FixedSingle

Button 1 Button 2Name Do not change BTNXText - E&XIT

CodePrivate Sub BTNX_Click()EndEnd Sub

Private Sub TXTFOCUS_GotFocus()LBLFOCUS.Text = "The text box has the focus"End Sub

Private Sub TXTFOCUS_LostFocus()If TXTFOCUS.Text = "" Then MsgBox "PLEASE ENTER SOME TEXT" TXTFOCUS. Focus ( )Else LBLF.OCUSText = TXTFOCUS.TextEnd If

35

Page 38: Visual Basic

11. Timer Control The Timer is an interesting control of Visual Basic which is not displayed at run time, but instead it helps the program by executing a piece of code given in its Timer() event every few seconds or as given in the time interval property of the timer. The properties listed below will help you in understanding the Sample Program that follows. Some of the properties are

Name The name of the timer controlEnabled If the timer is enabled then just like a clock it checks for the condition every few

seconds and then acts accordingly as specified by the programmer.Interval The time interval in milliseconds.

Pset MethodThe Pset Method draws a point at the X, Y co-ordinate that is specified by its parameter. The Pset method has an optional parameter called Step, which draws the point in relation to the CurrentX and CurrentY co-ordinates. For e.g., if CurrentX = 100 and CurrentY = 50, if you issue the statement

Form1.Pset Step (10,20)

A point is drawn at 110, 70, i.e., 10 units to the right of CurrentX and 20 units below CurrentY. The values of CurrentX and CurrentY are automatically updated to 110 and 70 respectively.

Program 21 – The Timer Control Program

Form Name FRMCLOCKText The Clock ProgramWindowState 2-Maximized

Label 1 Name LBLCLOCKText -BorderStyle 1-FixedSingleFont Size - 24

Timer 1 Name TMRCLOCKInterval 1000Enabled True

CodePrivate Sub TMRCLOCK_Tick()LBLCLOCK.Text = "TIME: " & Format(Now, "hh:mm:ss tt") & Chr(13) _

& "DATE: " & Format(Now, "dd/mm/yyyy")End Sub

36

Page 39: Visual Basic

12. Arrays

Data Types

Data Type Shortcut Notation RangeByte 0 To 255Integer % -32768 To 32767Long & -2,147,483,648 To 2,147,483,647Single Positive ! 1.401298E-45 To 3.402823E-38Single Negative ! - 3.402823E-38 To -1.401298E-45Double Positive # 4.94065645841247D-24 To 1.79769313486232D308Double Negative # -1.79769313486232D308 To - 4.94065645841247D-24Currency @ -922337203685477.5808 To 922337203685477.5807String $ Up to 2 billion charactersDate 1/1/0000 To 31/12/9999Boolean Logical ValuesVariant Any of the above types

E.g. Dim N As Integer Or Dim N%

ARRAYSThe declaration of an array specifies the array’s name and the maximum number of elements it can hold. All elements in an array must have the same data type. If the data type is variant, individual elements can contain different kinds of data.

By default, the first element of an array has index 0. The number that appears in parentheses in the Dim statement is the array’s upper limit and is one less than the array’s total capacity.

E.g.1. Dim A(15) As Integer

The above array contains 16 elements with index 0 for the first element and index 15 for the last (16th) element.

2. Dim A(10 To 15) As IntegerThe above array contains 6 elements with index 10 for the first element and index 15 for the last (6th) element.

Static VariablesAfter you declare a static variable and you execute the program for the first time, Visual Basic sets the value to 0. During the execution of a procedure, the value of the static variable changes to another value. When the procedure is executed again, the value of non-static variable is initialized back to zero. But it is not so for static variables.

There is a similarity between a variable declares in the general declaration area and a variable declared as a static variable in a procedure. In both cases, the variable retains it value as long as the program is in the execution stage. The difference is that a general variable is accessible to any procedure, whereas a static variable is accessible only to the procedure which declares it.

Dynamic ArraysSometimes, after creating the array you may want to change its size. This is possible if you create a dynamic array. A dynamic array can be resized at run time using the Redim Statement. A dynamic array is defined in the general declaration area of the form without specifying the upper and lower bounds.

37

Page 40: Visual Basic

Preserve KeywordIt is used to change the size of the array without losing the data in it, i.e., it redefines the array by preserving the elements of the previously defined (resized) array.

Control ArrayA control array is an array of controls, sharing the same name, type and event procedures. A control array has atleast one element and can grow to any number of elements depending on the memory and resources. Each element of a control array has its own property settings. Control arrays can consist of elements of the same type only. For e.g., a Button button and a text box cannot be part of the same control array. A control array can be created in two ways – by assigning the same name to more than one control or copying the existing control and pasting it on the same form.

Program 22 – The Digit Conversion Program

Form Name FRMDIGITSText The Conversion ProgramWindowState 2-Maximized

Text 1 Name TXTDIGITSText -

Label 1 Label 2Name Do not change LBLDIGITSText Enter a Number -BorderStyle Do not change 1-Fixed SingleAutoSize True False

Button 1 Button 2 Button 3Name BTNOK BTNCLEAR BTNXText &OK &CLEAR E &XIT

CodeDim DIGITS(9) As String

Private Sub CMBTNCLEAR_Click()LBLDIGITS.Text = " "TXTDIGITS.Text = " "TXTDIGITS.Focus ( )End Sub

Private Sub BTNEXIT_Click()EndEnd Sub

Private Sub Form_Load()DIGITS(0) = "ZERO"DIGITS(1) = "ONE"DIGITS(2) = "TWO"DIGITS(3) = "THREE"DIGITS(4) = "FOUR"DIGITS(5) = "FIVE"DIGITS(6) = "SIX"DIGITS(7) = "SEVEN"DIGITS(8) = "EIGHT"DIGITS(9) = "NINE"End Sub

Private Sub BTNOK_Click() If Not IsNumeric(TXTDIGITS.Text) Then

38

Page 41: Visual Basic

MsgBox "INVALID NUMBER" TXTDIGITS.Text = " " TXTDIGITS.Focus ( )Else Dim N, L, CTR N = TXTDIGITS.Text L = Len(N)

For CTR = 1 To L LBLDIGITS.Text = LBLDIGITS.Text & " " & DIGITS(Mid(N, CTR, 1)) NextEnd IfEnd Sub

Program 23 – The Control Array Program

Form Name FRMMOONText The Moon ProgramWindowState 2-Maximized

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\ElementsImageList1 Images Moon01 to Moon08

PictureBox1 Name IMGMOON

Button 1 Button 2Name BTNSTART BTNXText &START E&XIT

Timer 1 Name TMRMOONInterval 250Enabled True

Code

39

Page 42: Visual Basic

Option ExplicitDim GMOON, GCM

Private Sub BTNS_Click()If GMOON = 0 Then GMOON = 1 BTNSTART.Text = "&STOP"Else GMOON = 0 BTNSTART.Text = "&START"End IfEnd Sub

Private Sub BTNX_Click()EndEnd Sub

Private Sub Form_Load()GMOON = 0GCM = 0End Sub

Private Sub Timer1_Timer()If GMOON = 1 Then IMGMOON.Image = ImageList1.Images(GCM) GCM = GCM + 1 If GCM = 8 Then GCM = 0 End IfEnd IfEnd Sub

Page 43: Visual Basic

13. Menus

Program 24 – The Menu Program

Form Name FRMMENUText The Menu ProgramWindowState 2-Maximized

MenuStrip Name Text ShortcutMNUFILE &FILE -

MNUCOLOR &COLORMNURED &RED Ctrl +RMNUGREEN &GREEN Ctrl +GMNUBLUE &BLUE Ctrl +BMNUWHITE &WHITE Ctrl +WMNUCYAN &CYAN Ctrl +C

MNUX E&XIT Ctrl+XMNUSIZE &SIZE

MNUNOR &NORMAL Ctrl+NMNUMIN &MINIMIZE Ctrl+MMNUNOR MAXIMI&ZE Ctrl+Z

CodePrivate Sub MNUBlue_Click()Me.BackColor = Color.BlueEnd Sub

Private Sub MNUCyan_Click()Me.BackColor = Color.CyanEnd Sub

Private Sub MNUGreen_Click()Me.BackColor = Color.GreenEnd Sub

Private Sub MNUWhite_Click()Me.BackColor = Color.WhiteEnd Sub

Private Sub MNUMAX_Click()Me.WindowState = Form.WindowState.MaxmizedEnd Sub

Private Sub MNUMIN_Click()Me.WindowState = Form.WindowState.MinimizedEnd Sub

Private Sub MNUNOR_Click()Me.WindowState = Form.WindowState.NormalEnd Sub

Private Sub MNURed_Click()Me.BackColor = Color.RedEnd Sub

Private Sub MNUX_Click()EndEnd Sub

Page 44: Visual Basic

Program 25 – The Menu Program

Form Name FRMMENUARRText The Menu ProgramWindowState 2-Maximized

MenuName TextMNUFILE &FILE

MNUARRAY &ARRAYMNUS1 -MNUDIGITS &DIGITSMNUS2 -MNUDA &DYNAMIC ARRAYMNUS3 -MNUMOON &MOONMNUS4 -MNUX E&XIT

CodePrivate Sub MNUARRAY_Click()Me.HideFRMARRAY.ShowEnd Sub

Private Sub MNUDA_Click()Me.HideFRMDA.ShowEnd Sub

Private Sub MNUDIGITS_Click()Me.HideFRMDIGIT.ShowEnd Sub

Private Sub MNUMOON_Click()Me.HideFRMMOON.ShowEnd Sub

Private Sub MNUX_Click()EndEnd Sub

'FOR THE CODE OF BTNX OF THE ABOVE FORMS WRITE THE CODE'FRMMENUARR.SHOW'HIDE THE RESPECTIVE FORM

Program 34 – The Popup Menu Program(No form design)

Form Name FRMPMText The Popup Menu ProgramWindowState 2-MaximizedContextMenuStrip ContextMenuStrip1

ContextMenuStripName TextMNUSAVE &SAVEMNUPRINT &PRINT

Page 45: Visual Basic

CodePrivate Sub Form_MouseUp( )If e.Button = Windows.Forms.MouseButtons.Right Then Me.ContextMenuStrip1.Show ( )End IfEnd Sub

Private Sub MNUPRINT_Click()MsgBox "You have selected the print option"End Sub

Private Sub MNUSAVE_Click()MsgBox "You have selected the save option"End Sub

Program 26 – The Text Editor Program

Form Name FRMTEXT

Text The Text EditorWindowState 2-Maximized

MenuName TextMNUFILE &FILE

MNUX E&XITMNUEDIT &EDIT

MNUCUT CU&TMNUCOPY &COPYMNUPASTE &PASTE

MNUFONT &FONTMNUBOLD &BOLDMNUITALIC &ITALICMNUUNDERLINE &UNDERLINEMNUREGULAR &REGULAR

TextBox1 Multiline TruePlace it at the top left corner below the menu bar

CodeDim B, I, UPrivate Sub Form_Resize( )TextBox1.Width = Me.WidthTextBox1.Height = Me.HeightEnd Sub

Private Sub Form_Load( )B = FalseI = FalseU = FalseEnd Sub

Private Sub MNUBold_Click()If B = True Then B = False mnuBold.Checked = FalseElse B = True mnuBold.Checked = TrueEnd IfFontStyle ( )

End Sub

Private Sub MNUItalic_Click()If I = True Then I = False mnuItalic.Checked = FalseElse I = True mnuItalic.Checked = True

Page 46: Visual Basic

End IfFontStyle ( )

End Sub

Private Sub MNURegular_Click()B = FalseI = FalseU = FalsemnuBold.Checked = FalsemnuItalic.Checked = FalsemnuUnderline.Checked = FalseFontStyle ( )End Sub

Private Sub MNUUnderline_Click()If U = True Then U = False mnuUnderline.Checked = FalseElse U = True mnuUnderline.Checked = TrueEnd IfFontStyle ( )End Sub

Private Sub MNUCOPY_Click()Clipboard.Clear ( )Clipboard.SetText (TextBox1.SelectedText)End Sub

Private Sub MNUCUT_Click()Clipboard.Clear ( )Clipboard.SetText (TextBox1. SelectedText)TextBox1. SelectedText = ""End Sub

Private Sub MNUX_Click()EndEnd Sub

Private Sub MNUPASTE_Click()TextBox1. SelectedText = Clipboard.GetTextEnd Sub

Page 47: Visual Basic

Public Sub FontStyle ( )If B = True And I = True And U = True Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing.FontStyle.Bold Or _

Drawing. FontStyle.Italic Or Drawing. FontStyle.Underline)End IfIf B = True And I = True And U = False Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold Or _

Drawing. FontStyle.Italic)End IfIf B = True And I = False And U = True Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold Or _

Drawing. FontStyle.Underline)End IfIf B = False And I = True And U = True Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Italic Or _

Drawing. FontStyle.Underline)End IfIf B = True And I = False And U = False Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold)End IfIf B = False And I = True And U = False Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Italic)End IfIf B = False And I = False And U = True Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Underline)End IfIf B = False And I = False And U = False Then TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Regular)End IfEnd Sub

Page 48: Visual Basic

Program 27– Menus with Arrays

Form Name FRMITEMSText Loading Items In A Menu At

RuntimeWindowState 2-Maximized

Button 1 Name BTNITEMSText CLICK HERE TO LOAD NEW ITEMS

MenuName TextMNUFILE &FILE

MNUITEMS &ITEMSMNUX E&XIT

CodePrivate Sub Command1_Click()Static intItemCountintItemCount = intItemCount + 1MNUITEMS.DropDownItems.Add(“Item” & intItemCount)End Sub

Page 49: Visual Basic

14. MICROSOFT ACCESS

DatabaseA database is a collection of records in an organized manner. For e.g., telephone diary.DBMS – Database Management SystemRDBMS – Relational Database Management System

Access is a DBMS as well as an RDBMS, i.e., it allows you to define relationships between different types of data and use them together.

Elements of an Access DatabaseThere are some important elements usually referred to as Objects in an Access Database. Types of objects: Tables: Any data that you enter in an Access database gets stored in a table. Queries: Allow you to ask questions about your data or make changes to the data. Forms: Used for viewing and editing information. Reports: Are useful for summarizing data and printing it. Macros: Perform one or more database actions automatically.

TablesThe most basic component of an Access Database is a Table, a collection of data arranged in rows and columns. The table consists of rows of information arranged under column headings, called Fields, that describe the type of information stored in each column. Each item of information is a Field Value and each row of is a Record.

Field TypesA field name can be upto 64 characters long, can contain letters, numbers, spaces and other characters except period (.), exclamation mark (!), accent grave (`) and brackets ([ ]). AutoNumber: Access automatically assigns a number to this filed when a record is added to the table. Currency: This type of field is used for monetary values. Date/Time: Stores dates, time, or a combination of the two. Hyperlink: This field holds hyperlink addresses that jump to web sites, database objects or other files. Lookup Wizard: A lookup field starts a wizard that places lookup constraints on a field. The looked up values

can come from a list you enter, a table or a query. Memo: Holds unlimited amount of text. Number: Stores numbers formatted in various ways. OLE Object (Object Linking & Embedding): It holds objects like pictures, Word Documents, etc. Text: Holds letters, numbers and other characters. Yes/No: holds values like True/False, Yes/No, Male/Female, etc. Access automatically displays the field as a

check box.

Input MaskInput mask provides a couple of different data entry checks like:

Ensure that a field value matches a certain patternAutomatically fill in constant characters like (-) or (())

Input Mask CharactersChar Purpose Char Purpose

0 Required number (0 – 9), no signs (+ / - ) allowed

a Optional letter or number

9 Optional number (0 – 9), no signs (+ / - ) allowed A Required letter or number# Optional number or space, signs allowed & Required character or spaceL Required letter (a – z) c Optional character or space

Page 50: Visual Basic

? Optional Letter (a – z) \ Next character in the mask to be displayed as a constant character

IndexesAccess uses indexes to speed up find operations, where it has to look for data in more than one field. Any table that is keyed automatically has a primary index created for its keyed field. You can also create your own indexes for other fields using the properties tab.

Record Navigation Bar Current Total No. Record No. of Records

First Previous Next Last New Record Record Record Record Record

RELATIONSHIPAccess relates tables using fields with common values.

Types of Relationships One – To – One: It exists when there is only one record on each side of the relationship for each linking value. One – To – Many: It exists where there can be more than one record for a linking value on one side of a

relationship. Many – To – Many: It exists where linking values can appear in multiple records on both sides of a relationship.

Referential IntegrityIt is a way to protect data in linking fields so you don’t end up with unrelated data.

Rules for Referential Integrity Cascade Update Related Fields: Changes the values in related records when the linking value in a master

record is changed. Cascade Delete Related Records: Deletes related records when the master record in a relationship is deleted.

CourseCourseCode Duration FeesCIS 1 yr 15000

DG 2 yrs 200000

Page 51: Visual Basic

CourseCourseCode Duration FeesMSCIT 3 mths 2210

Oracle 6 mths 27000Tally 1 mth 3500

Field Name Data Type SizeBatchCode Text 10 Indexed: Yes (No

Duplicates), Primary key

Days Text 6Time Text 12CourseCode LookupWizaed

Field Name Data Type SizeCourseCode Text 25 Indexed: Yes (No Duplicates), Primary

keyDuration Text 10Fees Number Long Integer

BatchBatchCode Days Time CourseCodeCIS0801 MWF 9.30-11.30 CISCIS0802 TTS 9.30-11.30 CIS

CIS0803 MWF 4.30-6.30 CISCIS0804 TTS 4.30-6.30 CIS

DG0901 MWF 12-2 DGMSCIT01 MWF 8-10 MSCIT

MSCIT02 TTS 12-2 MSCITMSCIT03 MWF 2-4 MSCIT

TAL01 MWF 8-10 TallyORA01 TTS 8-10 Oracle

Page 52: Visual Basic

FORMS

AutoFormThe quickest way to create a form is using the AutoForm feature. There are 3 types of AutoForms: Columnar: A Columnar AutoForm shows only one record at a time in the Form view window. Tabular: A Tabular AutoForm displays multiple records at a time in the Form view window. Datasheet: In a Datasheet AutoForm, records are displayed in the same manner as they would appear in a

Datasheet window.

Creating a Columnar AutoForm Go to the Forms tab in the Database Window Click on New Select Autoform – Columnar Select the table from the drop-down list Click on OK Change the formatting effects if required Save the form

Creating a Tabular AutoForm Go to the Forms tab in the Database Window Click on New Select Autoform – Tabular Select the table from the drop-down list Click on OK Switch to the design view Change the object type of the ‘Course Code’ combo box to text box Right click on the form and select properties from the menu Change the options Allow Edits, Allow Deletions and Allow Additions to No Change the formatting effects if required Save the form

Creating a Form using the Form WizardThe Form Wizard allows you to: Select fields for the form from more than one table Choose the order in which fields appear on the form Choose the master table for the form (which determines the order of the form’s records), when the form includes

fields from more than one table Choose a layout for the form Choose a style for the form

Steps for Creating the Form: Go to the Forms tab in the Database Window Click on New Select Form Wizard Click on OK Select the table(s) and the required fields Click on Next Select the master table Click on Next Select the layout Click on Next Select a style Click on Next Change the names if required FinishFILTERSIt is a kind of search that checks for values in more than one field.

Page 53: Visual Basic

Filter Records Using One Field and One ValueIf you want to find records that match a value in just one field, you can use any of these techniques:

Filter By Selection: Allows you to select a value in the datasheet view or form view and click a button to display any matching records. Open any table in the datasheet view Select any value in the table Click on Filter by Selection on the toolbar To remove the filter, click on Remove Filter on the toolbar

Filter By Form: Displays a blank record, where you can either enter the value you want to find or choose it from a drop-down list Open any table in the datasheet view Click on Filter by Selection on the toolbar Select the condition Click on Apply Filter on the toolbar To remove the filter, click on Remove Filter on the toolbar

Filter For: Shows up a shortcut menu for any field, where you have to type the value you want to find. Open any table in the datasheet view Right click in any field Type the criterion in front of Filter For Press the Enter key To remove the filter, click on Remove Filter on the toolbar

Filter Excluding Selection: Looks for values other than what you have entered Open any table in the datasheet view Select any field value, you don’t want to see Right click and select Filter Excluding Selection To remove the filter, click on Remove Filter on the toolbar

Filter Using Multiple Criteria

AND Filters Filter By Selection Repeatedly

Repeat the steps under Filter By Selection (above) twice (for different fields)

Filter by Form Open any table in the datasheet view Click on Filter by Selection on the toolbar Select the condition Click on Apply Filter on the toolbar To remove the filter, click on Remove Filter on the toolbar

Filter For Repeat the steps under Filter For (above) twice (for different fields)

OR FiltersFilter by Form Filter by Form

Open any table in the datasheet view Click on Filter by Selection on the toolbar Select the condition (select the second condition in the Or tab) Click on Apply Filter on the toolbar To remove the filter, click on Remove Filter on the toolbar

QUERIESQueries are most often used to ask questions about your data. You can formulate simple queries that look for records in a single table or design complex queries that involve multiple tables.

Page 54: Visual Basic

Difference Between Filters and QueriesYou can do this With a Filter With a Query

Change the records you are currently viewing in Datasheet or form view Yes NoSave the view of selected records as a separate Database object No YesCreate a form or report based on a subset of records No YesChoose the fields you want to see No YesInclude fields from more than one table No Yes

Types of QueriesSelect Query: It finds the records satisfying the specified condition(s) and displays them whenever the query is executed.Make-Table Query: When you turn a select query into a make-table query, it writes the result to a completely new table.Update Query: You can make global changes to a table or update one table against another using this query.Append Query: It is used to add information from one table to another.Delete Query: Instead of deleting records from a table one by one, you can use a Delete Query to quickly delete an entire group of records.

Examples for Queries Simple Query

Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Batch, Course) Select the fieldsField Course Code Duration Fees Batch Code Days TimeTable Course Course Course Batch Batch BatchSort Ascending Ascending Save the query Click on Run on the toolbar

Look for Blanks Delete some of the addresses from the Stud_Info table Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud_Info) Select the fields

Field Stud_Info.* AddressTable Stud_Info Stud_InfoShow Select DeselectCriteria Is Null

Save the query Click on Run on the toolbar

Page 55: Visual Basic

Use a Yes/No Field Add a field to the Course table – Govt_Rec (Type – Yes/no) Select the Govt_Rec field for some records Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Course) Select the fields

Field Course.* Govt_RecTable Course CourseShow Select DeselectCriteria Yes

Save the query Click on Run on the toolbar

Look for a Range of Values Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud_Info) Select the fields

Field Stud_Info.* DOJTable Stud_Info Stud_InfoShow Select DeselectCriteria Between #7/1/00# and #7/31/00#

Save the query Click on Run on the toolbar

AND Query Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Course) Select the fields

Field Course.* Govt_Rec DurationTable Course Course CourseShow Select Deselect DeselectCriteria No Like “1*”

Save the query Click on Run on the toolbar

OR Query Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Course) Select the fields

Field Course.* Govt_Rec DurationTable Course Course CourseShow Select Deselect DeselectCriteria YesOr Like “2*”

Save the query Click on Run on the toolbar

Make a Table From a Query

Page 56: Visual Basic

Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (All the 3 tables) Select the fields

Field Stud_Code Name Surname Batch Code

Time Days Course Code

Duration Fees

Table Stud_Info Stud_Info Stud_Info Batch Batch Batch Course Course Course From the Query Menu, select the option Make Table Query Type the table name as ‘Student Details’ Save the query Click on Run on the toolbar It will confirm whether you want to paste the records into the new table Click on Yes

Find Duplicates with a QueryAccess has a wizard that can help you find duplicate records in a table. It asks you which field to check for duplicate values and shows the query result in a datasheet view Go to the Queries tab in the Database window Click on New Select Find Duplicates Query Wizard Select the table (Stud_Info) Click on Next Select the field for where you have duplicate records (Batch Code) Click on Next Select any additional fields that you want to see (None) Click on Next Type a name for the query (Batch Strength) Click on Finish

Find Unmatched Records with a QueryThe Find Unmatched Query Wizard finds records in one table that do not have matching values in one or more fields in another table. Go to the Queries tab in the Database window Click on New Select Find Unmatched Query Wizard Select the table (Course) Click on Next Select the table having unmatched values (Batch) Click on Next Click on Next (In this step, Access, displays the relation between the two tables) Select the fields that you want to see (All) Click on Next Type a name for the query Click on Finish

Page 57: Visual Basic

Append Query Create a new table ‘Stud’ with the same fields as ‘Stud_Info’ Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud_Info) From the Query Menu, select the option Append Query Select the table name as Stud Select fields from Stud_Info tot be appended to Stud

Field Stud_Info.*Table Stud_InfoAppend To Stud.*

Save the query Click on Run on the toolbar It will confirm whether you want to paste the records into the new table Click on Yes The records will be appended as many times as you execute the query

Update Query (Make changes in table) Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud) From the Query Menu, select the option Update Query Select fields that you want to update

Field CollegeTable StudUpdate To MLDCCriteria Dahanukar

Save the query Click on Run on the toolbar It will confirm whether you want to update the records Click on Yes

Update Query (Update one table against another) Delete the information in the DOJ field of Stud table Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud & Stud_Info) Set a relation between the Stud_Code field of the two tables From the Query Menu, select the option Update Query Select fields that you want to update

Field DOJTable StudUpdate To [Stud_Info].[DOJ]

Save the query Click on Run on the toolbar It will confirm whether you want to update the records Click on Yes

Page 58: Visual Basic

Delete Query Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Stud) From the Query Menu, select the option Delete Query Select the condition for deleting the records

Field Batch CodeTable StudDelete WhereCriteria Like “ADSE*”

Save the query Click on Run on the toolbar It will confirm whether you want to delete the records Click on Yes

Create a Calculated Field with a Query Go to the Queries tab in the Database window Click on New Select Design view Choose the tables to be added (Course) Select the fields you want to see

Field Course.* Staff Fees:[Fees]*0.5Table Course

Save the query Click on Run on the toolbar

REPORTSAutoReportIt is the quickest way to create a report for a table or query. There are two types of AutoReports Columnar AutoReport

Go to the Reports tab in the Database Window

Click on New Select AutoReport: Columnar Select the table Click on OK

Tabular AutoReport Go to the Reports tab in the Database

Window Click on New Select AutoReport: Tabular Select the table Click on OK

Page 59: Visual Basic

Creating a Report with the Report Wizard Go to the Reports tab in the Database Window Click on New Select Report Wizard Click on OK Choose the tables and the fields (Course – Course Code, Fees, Duration; Batch – Batch Code,

Time, Days) Click on Next Select the master table Click on Next Select the sort order Click on Next Choose a layout Click on Next Choose a style Click on Next Type a name for the report Click on Finish

15. Database Programming

A Visual Basic program has 3 distinct parts:

User Interface: It is that part of the program with which the user interacts. The interface is developed with Visual Basic. It contains forms that display the data and allow the user to modify the data. It also contains the code that requests the database services to perform different operations on the data.

Database Engine: A database such as Microsoft Access consists of tables that hold information, but it has no way to actually manipulate the information. That is where a database engine comes in. It is a software program that actually manages the information in the database. In case of Access, the database engine used is JET

DataStore: The datastore is the physical file that contains the data.

Program 28 – Course Table

User Interface

Database Engine

DataStore

Page 60: Visual Basic

Data Show Data Sources Add New Data Source Database New Connection Change Microsoft Access Database File OK Browse Select CIS.mdb OK Next no Next Tables (Select Course) Finish

From Data Sources Window Under CISDataSet Drag and place CourseCode, Duration and Fees on to the form. Delete CourseBindingNavigator

Form Name FRMCOURSEText Course DetailsWindowState 2-Maximized

Label1 Label 2 Label3 Label 4Text Course Code Duration Fees Search for Course

Text 1 Text 2 Text 3Name TXTCCODE TXTDUR TXTFEES

Button 1 Button 2 Button 3 Button 4 Button5Name BTNADD BTNMODIFY BTNSAVE BTNDELETE BTNCOUNTText &ADD &MODIFY &SAVE &DELETE &COUNT

Button 6 Button 7 Button 8 Button 9 Button 10Name BTNFIRST BTNPREVIOUS BTNNEXT BTNLAST BTNXText &FIRST &PREVIOUS &NEXT &LAST E&IT

Combo1 Name CMBCCODEText -

CodePublic Sub EnterData( ) txtCCode.ReadOnly = False txtDur.ReadOnly = False txtFees.ReadOnly = False cmbCCode.Enabled = False BtnSave.Enabled = True BtnAdd.Enabled = False BtnModify.Enabled = False BtnDelete.Enabled = False BtnCount.Enabled = False BtnFirst.Enabled = False BtnPrevious.Enabled = False BtnNext.Enabled = False BtnLast.Enabled = False BtnX.Enabled = FalseEnd Sub

Private Sub BtnX_Click( ) EndEnd Sub

Public Sub ViewData( ) txtCCode.ReadOnly = True txtDur.ReadOnly = True txtFees.ReadOnly = True cmbCCode.Enabled = True BtnSave.Enabled = False BtnAdd.Enabled = True BtnModify.Enabled = True BtnDelete.Enabled = True BtnCount.Enabled = True BtnFirst.Enabled = True BtnPrevious.Enabled = True BtnNext.Enabled = True BtnLast.Enabled = True BtnX.Enabled = True If Me.CourseBindingSource.Count > 0 Then Me.CourseBindingSource.MoveFirst( ) End IfEnd Sub

Private Sub FrmCourse_Load( ) ViewData( ) Me.CourseTableAdapter.Fill(Me.CISDataSet.Course) cmbCCode.DataSource = CISDataSet.Tables("Course") cmbCCode.DisplayMember = "CourseCode" cmbCCode.SelectedIndex = 0End Sub

Private Sub BtnFirst_Click( ) Me.CourseBindingSource.MoveFirst( )End Sub

Private Sub BtnLast_Click( ) Me.CourseBindingSource.MoveLast( )End Sub

Page 61: Visual Basic

End Sub

Private Sub BtnPrevious_Click( ) If Me.CourseBindingSource.Position <> 0 Then Me.CourseBindingSource.MovePrevious( )Else Me.CourseBindingSource.MoveFirst( ) End IfEnd Sub

Private Sub BtnNext_Click( ) If Me.CourseBindingSource.Position <> -1 Then Me.CourseBindingSource.MoveNext( )Else Me.CourseBindingSource.MoveLast( )End IfEnd Sub

Private Sub BtnCount_Click( ) MsgBox("Total number of courses = " & Me.CourseBindingSource.Count)End Sub

Private Sub BtnAdd_Click( ) EnterData() Me.CourseBindingSource.AddNew( )Private Sub BtnSave_Click( ) On Error GoTo SaveError Dim msg, btn, tit, ans msg = "Save the record?" btn = vbQuestion + vbYesNo tit = "Save" ans = MsgBox(msg, btn, tit) If ans = vbYes Then Me.CourseBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll _

(Me.CISDataSet) Else Me.CourseBindingSource.CancelEdit( ) End If ViewData() Exit SubSaveError: MsgBox("Error adding details") Me.CourseBindingSource.CancelEdit( ) ViewData()End Sub

Private Sub BtnModify_Click( ) EnterData( )End Sub

Private Sub BtnDelete_Click( ) Dim msg, btn, tit, ans, pos msg = "Delete this record?" btn = vbQuestion + vbYesNo tit = "Delete" ans = MsgBox(msg, btn, tit) If ans = vbYes Then pos = Me.CourseBindingSource.Position Me.CourseBindingSource.RemoveAt(pos) Me.TableAdapterManager.UpdateAll(Me.CISDataSet) Me.CourseBindingSource.MoveFirst( ) End IfEnd Sub

Private Sub cmbCCode_SelectedIndexChanged( ) Dim c Dim pos c = cmbCCode.Text pos = Me.CourseBindingSource.Find("CourseCode", c) Me.CourseBindingSource.Position = posEnd Sub

Page 62: Visual Basic

16. ActiveX ControlsProgram 29 –Project Add User Control

Label1 Label2 Label3Text Value1: Value2: Result:

Text1 Text2 Text3Name TxtValue1 TxtValue2 TxtResultTextAlignment Right Right RightReadOnly False False True

Command1 Command2 Command3 Command4 Command5Name BTNAdd BTNSub BTNMul BTNDiv BTNClearText + - * / C

CodeDim val1, val2 As Boolean

Private Sub BTNAdd_Click()Chk_numIf val1 = True And val2 = True Then TxtResult.Text = Val(TxtValue1.Text) + Val(TxtValue2.Text)End IfEnd Sub

Private Sub BTNClear_Click()TxtValue1.Text = ""TxtValue2.Text = ""TxtResult.Text = ""TxtValue1.SetFocusval1 = Falseval2 = FalseEnd Sub

Private Sub BTNDiv_Click()Chk_numIf val1 = True And val2 = True Then If Val(TxtValue2.Text) <> 0 Then TxtResult.Text = Val(TxtValue1.Text) / Val(TxtValue2.Text) Else TxtResult.Text = "Error" End IfEnd IfEnd Sub

Page 63: Visual Basic

Private Sub BTNMul_Click()Chk_numIf val1 = True And val2 = True Then TxtResult.Text = Val(TxtValue1.Text) * Val(TxtValue2.Text)End IfEnd Sub

Private Sub BTNSub_Click()Chk_numIf val1 = True And val2 = True Then TxtResult.Text = Val(TxtValue1.Text) - Val(TxtValue2.Text)End IfEnd Sub

Public Sub Chk_num()If Not IsNumeric(TxtValue2.Text) Then TxtValue2.Text = "" TxtValue2.SetFocus val2 = FalseElse val2 = TrueEnd IfIf Not IsNumeric(TxtValue1.Text) Then TxtValue1.Text = "" TxtValue1.SetFocus val1 = FalseElse val1 = TrueEnd IfIf val1 = False Or val2 = False Then MsgBox "Invalid Numbers", vbOKOnly + vbInformation, "Error" If val1 = False And val2 = False Then TxtValue1.SetFocus Else TxtValue2.SetFocus End IfEnd IfEnd Sub

Private Sub UserControl_Load()val1 = Falseval2 = FalseEnd Sub

Save it as SimpleCalc Form1 Toolbox WindowsApplication1 Components Drapg and SimpleCalc on the form

Page 64: Visual Basic

17. Web BrowserProgram 30

Form Name FRMBROWSERText Browser Application WindowState 2-Maximized

Label Text URL

TextBox Name TXTURL

Button Name BTNGOText &GO

WebBrowser

Code:Private Sub BTNGO_Click ( ) WebBrowser1.Navigate (txtURL.Text)End Sub