VISUAL BASIC 6.0 - PowerPoint PPT Presentation

About This Presentation
Title:

VISUAL BASIC 6.0

Description:

VISUAL BASIC 6.0 – PowerPoint PPT presentation

Number of Views:212
Updated: 12 October 2015
Slides: 98
Provided by: bimray8729
Tags:

less

Transcript and Presenter's Notes

Title: VISUAL BASIC 6.0


1
  • VISUAL BASIC 6.0

Mr. Bimal Kumar Ray LECTURER Dept of Information
Science Telecommunication Ravenshaw
University CUTTACK, ODISHA, INDIA
2
Graphical User Interface (GUI) Design
  • Should be under users controluser should be
    able to customize
  • Form should follow function
  • Visually and functionally consistent
  • Immediate feedback
  • Attempt to prevent user mistakes

3
Rapid Application Development (RAD)
  • Use of prebuilt objects to make program
    development much faster
  • Shorter development life cycles
  • Easier maintenance
  • Capability to reuse components

4
Characteristics or Features of VB
  • Provides visual objects (controls) that can be
    drawn onto a window (form)
  • Makes building the interface much easier
  • Object-oriented code structure
  • Code structured around objects
  • Easy to understand syntax
  • IntelliSense technology helps write code
  • Objects can be reused and extended through
    inheritance
  • Object -- anything real or abstract, about which
    you store both data and operations that
    manipulate the data
  • Class -- an implementation that can be used to
    create multiple objects with the same attributes
    and behavior
  • Object is and Instance of a Class

5
Characteristics or Features of VB
  • Attribute -- identifying characteristics of
    individual objects, such as name or color
  • Operation -- an activity that reads or
    manipulates the data of an object called service
    in OOD, in OOP called a method
  • Message -- has two parts name of object to which
    message is sent, name of operation that will be
    performed. In OOP called event
  • Event-driven language
  • Things happen in response to events
  • Examples of events mouse click, opening or
    closing a window
  • The user, not the program determines the sequence
    of operations

6
Program Development Life Cycle (PDLC)
  • Methodology
  • organized plan that breaks process into steps
  • Analyze the problem
  • Design the problem
  • Code the program
  • Test and debug program
  • Formalize solution
  • Maintain the program

7
Basic Introduction
  • Properties attributes of objects.
  • Controls label,text,check boxes, list boxes,
    combo,listbox etc.
  • Forms windows that contain applications
    controls.
  • Events messages sent to an object when the
    application runs
  • Event procedures in VB written in blocks of code
    called subroutines
  • Procedures operations or services.
  • include methods, functions, subroutines
  • Statement an instruction that can stand alone.
  • Code a group of statements.

8
Creating Visual Basic Applications
  • Create the interface(form)
  • Set the properties
  • Write the code

9
Creating Visual Basic Applications
10
Integrated Development Environment (IDE)
  • Provides an environment for creating the
    interfaces, writing and testing code, and making
    changes.
  • Create controls on a form and adjust their sizes.
  • Understand the events, properties, and methods of
    controls.
  • Understand how the code and events work in a VB
    program.
  • Open and save a VB project.
  • Understand the coding mechanics and the naming
    convention.
  • Run an executable without the IDE

11
Integrated Development Environment (IDE)
  • Menu bar provides many menu items
  • Examples include File,Edit,view,project,format
    etc menus.
  • Toolbar below menu bar
  • Provides shortcuts (icons) to the menu bar.
  • Toolbox
  • Contains various icons representing VB controls.
  • Project Explorer Window
  • Shows all forms and modules the current project
    contains.
  • Properties window
  • shows all the properties of the selected object.

12
Integrated Development Environment (IDE)
  • Design time
  • during which you build an application
  • When you are placing controls on the form
  • When you are writing code in the code window
  • Runtime
  • during which you use an application
  • When the code in your project comes to life,
    responding to events
  • Press Start on the Debug menu in the IDE
  • Press the F5 key in the IDE
  • Press the start button in the IDE

13
Coding
  • Comments
  • Used to provide begin with tick mark () or Rem
  • Appear green colour in the coding line
  • Line Continue
  • If you have to write a long statement, break into
    lines by using the underscore (_) character.

14
Interfaces of Visual Basic Objects
  • Forms and controls are objects
  • Objects have interfaces
  • Properties
  • typically relate to appearance of objects
  • Events
  • user or system actions recognized by the object
  • Procedures written to handle events
  • Methods
  • actions that objects are capable of performing

15
Properties
  • Special types of data associated with object
  • Most relate to appearance of objects
  • i.e. Label1.BackColor Color.Red
  • Some relate to behavior of objects
  • i.e. btnNext.Enabled True
  • Object and property separated by dot (. period)
  • Property must be given a value

16
Events
  • User or system actions the object recognizes
  • i.e. a button has a Click event
  • Event procedure
  • Procedure written to handle a specific event
  • Also called event handler
  • Syntax Private Sub ObjectName_Event
  • Code surrounded by Sub End Sub
  • Private refers to the scope of the procedure
  • Object and event separated by underscore
  • Examples private sub cmdok_click()...... End sub

17
Methods
  • Actions objects are capable of performing
  • i.e. Me.Close(),print (), unload() etc
  • Syntax Object.Method(Parameter List)
  • Parameter list arguments passed in to the method
  • Parameter list must be enclosed in parentheses,
    even if no parameters are required

18
Naming objects
  • When naming objects, be descriptive
  • Use standard prefixes, i.e. lbl for label, txt
    for text
  • Give the object a meaningful name
  • i.e. a label with text Name could be lblName
  • Change the object name in the Properties window
  • Name objects before placing code in the code
    window

19
Assignment Statements
  • Generate some sort of result
  • i.e. moving data from one location in memory to
    another
  • Syntax lblmsg.caption Welcome
  • Expression on right hand side of equation moved
    to memory location on left hand side
  • Most common statements in VB programs

20
Completing the Development Cycle
  • Program must be compiled into executable
  • When you test run your program, the IDE compiles
    and saves the executable
  • To run the program
  • Double-click the executable
  • Use the Run option off the Start menu
  • Add the executable to your Start menu

21
Toolbox and Properties List
object box
property list
property values
22
Tool Box
23
Controls in VB
  • Label    
  • The label is a very useful control for vb, it can
    also be used to display outputs.
  • One of its most important properties is Caption.
  • it can display text and numeric data .
  • You can change its caption in the properties
    window and also at runtime. 
  • Backcolor,Forecolor,font,autosize,border style ,
    back style alignment etc

24
Controls in VB
  • Text Box   
  • The text box is the control for accepting input
    from the user as well as to display the output.
  • It can handle string (text) and numeric data but
    not images or pictures.
  • Name, text,maxlength,multiline,password
    character, font,back color, forecolor etc
  • Events are change,click,dblclick,keyup,keypress,
  • mouseover, mousedown etc

25
Controls in VB
  • Command Button 
  • The command button is one of the most important
    controls as it is used to execute commands.
  • It displays an illusion that the button is
    pressed when the user click on it.
  • The most common event associated with the command
    button is the Click event, and the syntax for the
    procedure is
  • Private Sub Command1_Click ()
  • Statements
  • End Sub

26
Controls in VB
  • Combo Box 
  • The function of the Combo Box is also to present
    a list of items where the user can click and
    select the items from the list. 
  • the user needs to click on the small arrow head
    on the right of the combo box to see the items
    which are presented in a drop-down list.
  • In order to add items to the list, you can also
    use the AddItem method.
  • Exp combo1.additem IST

27
Controls in VB
  •  List Box
  • The function of the List Box is to present a list
    of items where the user can click and select the
    items from the list.
  • In order to add items to the list, we can use
    the AddItem method.
  • Common methods are removeitem,clear,listcout,
  • listindex.

28
Controls in VB
  •  Check Box
  • The Check Box control the user  selects or
    unselects an option.
  • When the Check Box is checked, its value is set
    to 1 and when it is unchecked, the value is set
    to 0.  
  • A user select any number of checkboxes at the
    same time.

29
Controls in VB
  • Scroll Bars
  • Scroll bar in most of the Windows applications. A
    scroll bar is a very important element of a
    software.
  • if you have to scroll down or scroll up a page.
  • Two types of scroll bars are there in the VB
    environment HScrollBar (Horizontal Scroll Bar)
    and VScrollbar(Vertical Scroll Bar).
  • The Value property returns the scroll bar
    position's value.

30
Controls in VB
  • Scroll Bars
  • The Min property sets/returns the minimum value
    of a scroll bar positionThe Max property
    sets/returns the maximum value of a scroll bar
    position.
  • The SmallChange property sets/returns the amount
    of change to Value property in a scroll bar when
    the user clicks on a scroll arrow button.
  • The LargeChange property sets/returns the amount
    of change to Value property in a scroll bar when
    the user clicks on the scroll bar area.

31
Data Types in Visual Basic
  • Byte a numerical data types holding less than
    values 256
  • Integer holding numbers without a decimal point
    values 32767
  • Long - Long integer ( 8 bytes of storage)
  • Single holding numbers with a decimal point ( 4
    bytes storage)
  • Double - holding numbers with a decimal point ( 8
    bytes storage)
  • Decimal - same as double 16 bytes storage
  • Currency Dollar amounts
  • String - Character and alphanumeric data
    (text/string)
  • Char uses two characters
  • Object - Any object reference such as Word
    document
  • Variant - default, can hold any data type
  • Boolean - True or false
  • Date - From Jan 1, 100 to Dec 31, 9999

32
Variables, Declarations and Constants
  • Variables - A variable represents an area of
    storage in the computer's memory.
  • - A unique named storage location that contains
    data that changes during program execution.
  • Constant - A unique named storage locations that
    contains data that does not change during program
    execution.
  • Local variables - declared within a procedure or
    function.
  • Global variables - declared in the general
    section of the vb application.
  • Scope variables- Scope refers to how widely
    variable is recognized throughout program.

33
Variable Declarations
  • Declare variables using the Dim or Static
    statements
  • Dim statement - value of variable pre reservation
    only until procedure ends
  • Static statement - value of variable pre-
    reservation the entire time the application is
    running
  • Must give the variable a name
  • Syntax Dim variable name As datatype
  • Dim is required variable name As is required
    datatype
  • Exp Dim x as single
  • Defines a variable named x as a single data type

34
Variable Declaration Rules
  • Must begin with an alphabetic character
  • Can begin with letter or underscore, but not a
    number
  • Must be unique name with same scope
  • Must be variable name less 255 characters
  • variable name should not keyword
  • (do, while,wend,bold,underline,size etc
    )
  • variable name can not contain a period.
  • variable name can not contain spaces.

35
Declaring Constants
  • Some constants are predefined
  • Known as system constants
  • Examples include True and False
  • Others defined and declared before used
  • Known as symbolic constants
  • Must be declared with Const statement
  • Syntax Const constantname As datatype value
  • To declare a constant Const x hello
  • Defines the constant x and assigns a value
  • Const pi As Single pi 3.145
  • Const y As Integer y 100

36
Scope variable
  • The scope is where a variable is visible and
    usable.
  • Declared inside a function only within that
    function (local variable)
  • Declared outside a function available
    everywhere Except the function (global variables)
  • Can use keyword global to make a variable within
    a function have global scope.
  • Super global variables available everywhere
    including functions.

37
Module-level variables
  • A  Module-level variables can be declared with a
    Dim or Private statement at the top of the module
    above the first procedure definition.
  • A variable that is recognized among all of the
    procedures on a module sheet is called a
    "module-level" variable.
  • A module-level variable is available to all of
    the procedures in that module, but it is not
    available to procedures in other modules.
  • A module-level variable remains in existence
    while VB is running until the module in which it
    is declared is edited.
  • there is no difference between Dim and Private.
  • (Note that module-level variables cannot be
    declared within a procedure.)
  • Dim X as Integer ' Module-level
    variable.
  • Private Y as Integer ' Module-level
    variable. 

38
Control Flow statement
  • VB provides two types of control flow statement
  • 1) If statement
  • 2) Select Case statement
  • The If Statement If statement of VB comes in
    various forms are given below
  • 1) If..Then Statement
  • 2) If..Then..Else Statement
  • 3) If..Then..ElseIf Statement
  • 4) Nested Ifs

39
If..Then Statement
  • Def. An If..Then statement tests a particular
    condition if the condition evaluates to true, a
    course-of-action is followed otherwise it is
    ignored.
  • Syntax
  • If (boolean expression) Then
  • statements
  • End If

40
If..Then Statement
  • Example 1
  • If (Numgt0) Then
  • Print It is a positive number
  • End if
  • Example 2
  • If Text1.Textgt18 Then
  • text2.text You are eligible to vote
  • End if
  • Example 3
  • If (no mod 20) Then
  • label1.caption It is a even number
  • End if

41
If..Then..Else Statement
  • If..Then..Else statement provides an alternate
    choice to the user i.e. if the condition is true
    then a set of statements are executed otherwise
    another set of statements are executed.
  • Syntax
  • If (boolean Expression) Then
  • VB Statement(s)
  • Else
  • VB Statement(s)
  • End If

42
Examples of If..Then..Else
  • Example 1
  • If Text1.Textgt18 Then
  • Print You are eligible to vote
  • Else
  • Print Sorry, You are not eligible to vote
  • End If
  • Example 2
  • If no Mod 20 Then
  • Text2.Text It is an Even Number
  • Else
  • Text2.TextIt is an Odd Number
  • End If

43
If..Then..ElseIf Statement
  • If..Then..ElseIf statement is used to test a
    number of mutually exclusive cases and only
    executes one set of statements for the case that
    is true first.
  • Syntax
  • If (Boolean Expression) Then
  • Statement(s)
  • ElseIf (Boolean Expression 2) Then
  • Statement(s)
  • ElseIf (Boolean Expression 3) Then
  • Statement(s)
  • Else
  • Statement(s)
  • End If

44
Example of If..Then..ElseIf
  • If (Agelt4) Then
  • Print Your rate is free.
  • ElseIf (Agelt12) Then
  • Print You qualify for the childrens rate.
  • ElseIf (Agelt65) Then
  • Print You must pay full rate
  • Else
  • Print You qualify for the seniors rate.
  • End If

45
Nested Ifs
  • A nested If is an if that has another If in its
    ifs body or in its elses body. The nested if
    can have one of the following three forms
  • 1. If (expresssion 1) Then
  • If (expression 2 ) Then
  • Statement 1
  • Else
  • Statement 2
  • End If
  • Else
  • body-of-else
  • End If

46
Nested Ifs
  • 2. If (expression 1) Then
  • body-of-if
  • Else
  • If (expression 2) Then
  • Statement-1
  • Else
  • Statement-2
  • End If

47
Nested Ifs
  • 3) If (expression 1) Then
  • If (expression 2) Then
  • Statement-1
  • Else
  • Statement-2
  • End If
  • Else
  • If (expression 3) Then
  • Statement-3
  • Else
  • Statement-4
  • End If
  • End If

48
Example of Nested Ifs
  • If Numgt0 Then
  • Print It is a positive number
  • Else
  • If Numlt0 Then
  • Print It is a negative number
  • Else
  • Print The number is equal to zero
  • End If
  • End If

49
Select-Case Statement
  • Select-Case is a multiple branching statement and
    is used to executed a set of statements depending
    upon the value of the expression. It is better to
    use Select-Case statement in comparison to
    If..Then..ElseIf Statement when the number of
    checks are more. There are 3 different forms of
    using Select-Case statements and are given below

50
Different forms of Select-Case
  • 1. Select Case Simplest Form Exact match
  • Select Case Expression
  • Case Value
  • one or more visual basic statements
  • Case Value
  • one or more visual basic statements
  • Case Else
  • one or more visual basic statements
  • End Select

51
Example of Form 1
  • Select Case byMonth
  • Case 1,3,5,7,8,10,12
  • number_of_days31
  • Case 2
  • number_of_days28
  • Case 4,6,9,11
  • number_of_days30
  • End Select

52
Syntax of Form 2
  • Select Case Second Form Relational Test
  • Select Case Expression
  • Case is relation
  • one or more visual basic statements
  • Case is relation
  • one or more visual basic statements
  • Case Else
  • one or more visual basic statements
  • End Select

53
Example of Form 2
  • Select Case marks
  • Case Is lt 50
  • Result Fail
  • Case Is lt 60
  • Result Grade B
  • Case Is lt 75
  • Result Grade A
  • Case Else
  • Result Grade A
  • End Select

54
Third Form of Select Case
  • Select Case Third Format Range Check
  • Select Case Expression
  • Case exp1 To exp2
  • one or more visual basic statements
  • Case exp1 To exp2
  • one or more visual basic statements
  • Case Else
  • one or more visual basic statements
  • End Select

55
Example of Form 3
  • Select Case Age
  • Case 2 to 4 Print Nursery
  • Case 4 to 6 Print KG
  • Case 6 to 10 Print Primary
  • Case Else Print Others
  • End Select

56
Looping Structures
  • VB offers broadly following three types of
    looping structures
  • For..Next
  • Do Loop
  • a) Do While..Loop
  • b) Do..Loop While
  • c) Do Until..Loop
  • d) Do..Loop Until
  • While..Wend

57
For..Next Statement
  • This type of statement is used when the user
    knows in advance how many times the loop is going
    to be executed.
  • Syntax
  • For ltcounter Variablegtltstart_valgt To ltend_valgt
    Step ltincrement/Decrement Valuegt
  • One or more VB Statements
  • Next ltcounter Variablegt

58
Examples
  • Example 1 Generate natural nos from 1 to 100
  • For x 1 To 100
  • Print x
  • Next x
  • Example 2 Generate first 20 even nos.
  • For no 2 to 40 Step 2
  • Print no
  • Next no
  • Example 3 Generate odd nos from 100 to 30 in a
    list box.
  • For x 99 to 31 Step -2
  • List1.AddItem(x)
  • Next x
  • Example 4 Generate table of any number N.
  • Nval(text1.text)
  • For T 1 To N
  • Print N T NT
  • Next T

59
Do..Loop Structures
  • Do While..Loop Do While loop is an entry
    controlled loop in which the condition is placed
    at the entry point. This statement executes the
    statements specified in the body of the loop till
    the condition evaluates to true. The loop may not
    be executed at all the if the condition is
    initially false.
  • Syntax
  • Do While ltcondition or boolean expressiongt
  • One or more VB Statements
  • Loop

60
Examples
  • Example 1
  • Do
  • num InputBox (Enter a number)
  • sum sum num
  • Loop While num lt gt 0
  • Here the statements inside the loop will be
    executed once no matter what the comparison test
    evaluates to.

61
Array
  • An array is collection of variables of the same
    type that are referenced by a common name.
  • To refer to a particular location or element in
    the array, we specify the array name and the
    array element position number.
  • Each index number in an array is allocated
    individual memory space.
  • We can declare an array of any of the basic data
    types including variant, user-defined types and
    object variables.
  • The individual elements of an array are all of
    the same data type.

62
Array
  • Declaring array
  • Syntax dim ltarray namegt (ltmax index in arraygt)
    as data type
  • Dim x (5) As Integer
  • In the above examples x is the name of the array,
    and the number 5 included in the parentheses is
    the upper limit of the array. The above
    declaration creates an array with 5 elements,
    with index numbers running from 0 to 4.
  •  Dim x (1 To 6) As Integer
  • If we want to specify the lower limit, then the
    parentheses should include both the lower and
    upper limit a long with the To keyword.

63
Array Example
  • Creates array enter a range number print the
    total and their average.
  • Private Sub Command1_Click()
  • Dim arr(5) As Single, index As Integer, sum As
    Single
  • Dim no As Integer
  • no InputBox("Enter a range number")
  • For index 1 To no
  • arr(index) InputBox("enter a number")
  • Next
  • For index 1 To no
  • sum sum arr(index)
  • Next
  • Print " Total " sum
  • Print " The Average is " sum / no
  • End Sub

64
Functions
  • A function is a procedure that performs a
    specific task and returns a value.
  • A function procedure is a separate procedure
    that can take arguments, perform a series of
    statements, and change the value of its
    arguments.
  • The function will return a value to the calling
    subroutine based on the code that it contains.
  • syntax
  • Private/public Function fun_name (ByVal
    variable list as datatype) As datatype  
  •   body of function
  • End Function

65
Function Example
  • Write a function that received two numbers and
    returns the additions
  • Private Function Add (ByVal x as Integer,
    ByVal y as Integer) As Integer
  •     Add x y
  • End Function   
  • Private Sub Command1_Click ()
  •    Dim a ,b, c as Integer 
  •    a val(text1.text)
  • b val(text2.text)
  •   c Add (a, b)    
  • text3.text c
  • End Sub

66
LIBRARY FUNCTIONS
  • String Function
  • Lcase, Ucase, Len, Trim, Ltrim, Rtrim,, Left,
    Right, Mid, asc, Chr, strreverse
  • Number Function
  • Val, sgn, rnd ,format, int
  • Date function
  • Now, date, time,day,month,year, hour,minute,
    second

67
Subroutine
  • A subroutine is like a function, but it does not
    return a value.
  • Both a function and a sub (sub for subroutine)
    are blocks of code.
  • You can pass parameters to both subs and
    functions.
  • Parameters may be passed by value or by
    reference.
  • The Function or Subroutine receives a pointer to
    the original variable or object.
  • Any changes made in the Subroutine are made
    directly to the original variable or object.

68
Writing a Sub Procedure
  • Declared with Sub keyword
  • Syntax Private/Public Sub SubName(Parameter
    List)
  • Private/Public are optional access modifiers
  • SubName is any valid name
  • Parameter List is a list of parameters
    (arguments) passed to the sub
  • Ends with End Sub statement

69
Sub Procedure Example
  • Write a procedure that received a number and
    checked whether the even or odd number
  • Private Sub demo( x As Integer )
  • If x Mod 2 0 Then
  • MsgBox "this number is even"
  • Else
  • MsgBox "this number is odd"
  • End If
  • End Sub
  • Sub Command1_Click()
  • Dim a As Integer
  • a InputBox ("enter any number")
  • Call demo (a) ' procedure calling
  • End Sub

70
Calling a Sub Procedure
  • Refer to the Sub by name
  • Pass in required arguments (parameters)
  • Arguments must be passed in the order given in
    the Sub header
  • Arguments must be of same type as specified in
    the Sub header
  • It is possible to pass data by parameter name
  • Syntax SubName(Parameter1Argument1)
  • Parameter1 represents name of parameter
  • Argument1 represents argument passed

71
Terminating a Procedure Before Reaching the End
  • Exit Sub statement terminates a Sub
  • Often included inside an If block or loop if you
    want the procedure to end if a certain condition
    is met
  • Return statement also terminates the sub
  • Control of program returned to calling procedure

72
Sub Procedure Modifiers
  • Access modifiers declare scope of procedure
  • Private procedures recognized only in the current
    form or class
  • Public procedures accessible to all modules in
    project
  • Parameters contain data the procedure needs to
    perform its task
  • ByVal keyword indicates the actual value of
    variable is passed to procedure
  • If value is changed by procedure, original value
    of variable is unchanged
  • ByRef keyword indicates variable memory address
    is passed to procedure
  • If value is changed by procedure, memory address
    is updated

73
MDI FORM(Multiple Document Interface)
  • MDI application allows us to display multiple
    documents at the same time, with each displayed
    in its own windows.
  • MDI applications as they allow opening of several
    documents one bye one at a time.
  • MDI allows you to create an application that
    maintains multiple forms within a single
    container form.
  • MDI application must have at least two forms, the
    parent form and two or more child forms.
  • An MDI application can contain only one MID form
    on a project.
  • Any form can be made an MDI child form by setting
    its MDIChild property to true.
  • Now add an MDI form to your project by following
    step
  • Project-gt Add MDI Form-gtopen.

74
To Create Menu Control in The Menu Editor
  • Select the form.
  • Form the tool menu choose menu editor
  • In the caption text box, type the text for the
    first menu title that you want on the menu bar.
  • In the name text box type the name, which you
    will use to refer to the menu control code.
  • Click on the left/right arrow and button to
    change the label of the control.
  • Set the properties of the control if you choose,
    you can do this in the menu editor. Choose next
    to create another menu control.
  • You can also click on the up arrow and down arrow
    buttons to move controls along the existing menu
    control.
  • Choose OK to close the menu editor.

75
Creating Menus with the Menu Editor
76
CREATING TOOL BARS
  • Toolbars are an extremely useful enhancement to
    menus.
  • They provide mouse prevent shotcuts to menu
    options.
  • When designing tool bar it is important to
    consider the designed sanitation.
  • You may want to use standardized button or
    icons

77
Adding Images to Toolbar
  • Now you need to add some images on the toolbar to
    do the followings.
  • Add an image list to your form and set its name
    property to image Toolbar.
  • This control was added to your toolbox when you
    added the Microsoft common control 6.0.
  • Open the property pages dialog box by selecting
    custom from the properties window.
  • When the property pages dialog box appears, click
    on the images tab. So you can add some images.

78
Common Dialog Boxes
  • The common dialog box in visual basic is an
    insertable control that allows users to display a
    number of common dialog boxes in their program.
  • In Visual Basic you can use Dialog boxes for
    common events such as selecting a colour ,font,
    open,save ,print and help.
  • Visual Basic displays a dialog box that requests
    more information before the command is carried
    out.
  • Displays a message in a dialog box, waits for the
    user to click a button, and then returns an
    integer indicating which button the user clicked.
  • To use this control, you must select Microsoft
    Common Dialog Control 6.0 on the Controls tab in
    the Components window.

79
Common Dialog Boxes
  • Predefined standard dialog boxes for
  • Font and Color selection
  • File Opening and Saving
  • Printing and Previewing
  • select Project -gt Components-gt Microsoft Common
    Dialog Control 6.0 then, the control icon will
    appear in your toolbox and you can add it as a
    form like any other control.
  • Use CommonDialog method to display the common
    dialog box at run time
  • Code must be written to retrieve and use the
    choice made by the user in the common dialog box

80
Color Dialog Box Coding
  • Private Sub cmdColour_Click()
  • On Error GoTo errhandler
  • CommonDialog1.CancelError True
  • CommonDialog1.ShowColor
  • Me.BackColor CommonDialog1.Color
  • Exit Sub
  • errhandler
  • Select Case Err
  • Case 32755 ' Dialog Cancelled
  • MsgBox "you cancelled the dialog box"
  • Case Else
  • MsgBox "Unexpected error. Err " Err " "
    Error
  • End Select
  • End Sub

81
Save Dialog Box Coding
  • Private Sub cmdSave_Click()
  • On Error GoTo errhandler
  • CommonDialog1.CancelError True
  • CommonDialog1.Flags cdlOFNHideReadOnly
    cdlOFNOverwritePrompt cdlOFNPathMustExist
  • CommonDialog1.Filter "All Files (.).RTF
    (.rtf).rtfText Files (.txt).txt
  • CommonDialog1.Filename ""
  • CommonDialog1.ShowSave
  • Text1.Text "File Selected "
    CommonDialog1.Filename
  • Exit Sub
  • errhandler
  • Select Case Err
  • Case 32755 ' Dialog Cancelled
  • MsgBox "You cancelled the dialog box"
  • Case Else
  • MsgBox "Unexpected error. Err " Err "
    " Error
  • End Select
  • End Sub

82
CommonDialog
  • Color and Font Dialogs

83
Introduction to Working with Databases in Visual
Basic
  • Database
  • The storage of different types of data in such a
    way that the data can be easily manipulated and
    retrieved by an end user.
  • A database is composed of fields, records, and
    tables.
  • Multiple computers can be connected to the same
    database.
  • VB can be used to work with existing databases.
  • VB provides Microsoft Access database with an
    .mdb extension.
  • VB can be used to create a user-friendly
    front-end to a database.

84
The Data Control
  • The data control is essential to working with
    databases in VB.
  • It uses an internal pointer to point to the
    current record.
  • DatabaseName property must be set to the path
    name of the database.
  • RecordSource property must be set to the table of
    the database.
  • Textboxes and other controls can be bound to a
    data control by assigning their DataSource
    property to the data control.
  • The bound controls DataField property is set to
    a field of the DataSource table.
  • The Recordset object represents the records in
    the database.

85
RecordSet Methods
  • There are several useful methods for the
    Recordset object
  • MoveFirst - move to first record
  • MoveLast - move to last record
  • MoveNext - move to next record
  • MovePrevious - move to previous record
  • AddNew - add a new record (save by moving to new
    record or using UpdateRecord method)
  • Delete - delete current record
  • UpdateControls - make bound controls the same as
    database

86
Recordset Properties
  • There are main useful properties for the
    Recordset object
  • AbsolutePosition - the current position of
    pointer
  • RecordCount - the number of records in the
    Recordset
  • BOF (EOF) - True if at Beginning (End) of File
  • Bookmark - A unique identification of each
    record
  • FindFirst - to find first character of a matching
    record
  • NoMatch -property is true, no record matches

87
Data Access Objects
  • Visual Basic application acts as a front-end to
    the database
  • Visual Basic application provides the interface
    between the user and the database
  • interface allows the user to tell the database
    what he or she needs
  • allows the database to respond to the request
  • displaying the requested information in some
    manner

88
Data Access Objects
  • A Visual Basic application cannot directly
    interact with a database
  • There are two intermediate components between the
    application and the database
  • data control
  • database engine

89
  • The relationship between the data control, its
    two primary properties (DatabaseName and
    RecordSource), and the Recordset object is

90
  • The relationships between a data bound control
    (DataSource and DataField properties) and the DAO
    data control (Recordset property) are

91
Jet Database Engine
  • Data control
  • It connects the application to the database via
    the database engine.
  • It is the  connected  between the application and
    the engine, passing information back and front th
    between the two application
  • It is a Visual Basic object
  • Jet Database Engine
  • It is the heart of a Visual Basic database
    management system
  • Having this engine saves programmers a lot of
    work.
  • The database engine native to Visual Basic is
    known as the
  • Jet engine.
  • It is the same engine used by Microsoft Access
    for database management.
  • it is primarily used to work with Access
    databases, but it can also work with others.
  • It requires less code to connect to an existing
    database
  • View all information within that database
  • Insert, delete, modify any and all information
    within that database

92
Data Access Object (DAO)
  • It is a structure of objects for accessing
    databases through your code.
  • All the functionality of the Data control is also
    available to your code, through the DAO.
  • Record Set
  • Record sets are objects that represent
    collections of records from one or more tables.
  • You cant access the tables of a database
    directly. The only way to view or manipulate
    records is via RecordSet object.
  • A RecordSet is constructed of columns and rows
    and is similar to a table. But it can contain
    data from multiple table.
  • Three types of RecordSets are
  • DynaSets ? Which are updatable views of data
  • SnapShots ? Which are static( read only) views
    of data
  • Tables ? Which are direct views of
    tables.

93
DAO Data Control Properties
  • Important properties of this data control are
  • Caption displayed on the data control.
  • Connect Type of database. Default is Microsoft
    Access (or Jet).
  • DatabaseName Returns or sets the name of the
    source DB for the data
  • control. Must be a
    fully qualified path and file name.
  • Exclusive Indicates whether the underlying
    database is opened for single- user or
    multi-user access.
  • ReadOnly Indicates whether the data can be
    edited or not.
  • Recordset A set of records defined by a data
    controls Connect,
  • DatabaseName, and
    RecordSource properties.
  • Run-time only.
  • RecordsetTypeIndicates type of Recordset you
    want data control to create
  • RecordSource Determines the table (or virtual
    table) the data control is attached to.

94
DAO Data Control Recordset Methods
  • Important Recordset methods are
  • AddNew Adds a new record to the Recordset.
  • Update Saves the current contents of all data
    bound controls.
  • CancelUpdate Used to cancel any pending updates
  • (either with Edit or
    AddNew method)
  • Close Closes a Recordset.
  • DeleteThe current record is deleted from the
    Recordset.
  • Edit Places the current record in the Recordset
    into edit mode.
  • Requery Updates the data in a Recordset object
    by re-executing the query on which the object
    is based.
  • MoveFirst/ MoveLast/ MoveNext/ MovePrevious
  • Moves the current record pointer to the first
    record in the Recordset.

95
DAO Database Connection Examples
  • Dim db As Database
  • Dim rs As Recordset
  • Private Sub Form_Load()
  • Set db OpenDatabase("d\bkr1.mdb")
  • Set rs db.OpenRecordset("select from sim",
    dbOpenDynaset)
  • End Sub
  • Private Sub cmdnext_Click()
  • rs.MoveNext
  • If rs.EOF Then
  • rs.MoveFirst
  • End If
  • Text1.Text rs!roll
  • Text2.Text rs!Name
  • Text3.Text rs!mark
  • End Sub

96
DAO Database Connection Examples
  • Private Sub cmdprev_Click()
  • rs.MovePrevious
  • If rs.BOF Then
  • rs.MoveFirst
  • End If
  • Text1.Text rs!roll
  • Text2.Text rs!Name
  • Text3.Text rs!mark
  • End Sub
  • Private Sub cmdnew_Click()
  • rs.AddNew
  • Text1.Text
  • Text2.Text
  • Text3.Text
  • Text1.setfocus
  • End Sub

Private Sub cmdedit_Click() rs.Edit rs!roll
Text1.Text rs!Name Text2.Text rs!mark
Text3.Text rs.Update rs.Bookmark
rs.LastModified Text1.Text "" Text2.Text
"" Text3.Text "" MsgBox "successfully modify
your data", vbInformation End Sub
97
THANK YOU
Write a Comment
User Comments (0)
About PowerShow.com