Copyrights © 2012 Jatin Kotadiya. All Rights Reserved . Powered by Blogger.

Friday, October 26, 2012

VISUAL BASIC



Ch. No. 1 Introduction
Introduction
Visual Basic is a high level programming language which is developed from the earlier DOS version called BASIC. BASIC means “Beginners All-purpose Symbolic Instruction Code”.
Visual Basic is a tool that allows us to develop Windows (Graphical User Interface - GUI) applications. The applications have a familiar appearance to user.
VB is GUI based because it allows us to create new windows called forms. We will use the toolbox to add various elements called controls.
Visual Basic 6.0 is Rapid Application Development (RAD) tool available either as a stand-alone product or as a part of the Visual Basic 6.0 suite of tools.
It is very easy programming language to learn.

Editions of Visual Basic
Learning: It consists of all necessary tools required to build main stream windows application.
Professional: It includes advanced features such as tools to develop ActiveX and Internet controls.
Enterprise: In addition to all features in professional edition it also includes tools such as Visual SourceSafe, Automation and Component Manager.

Features of Visual Basic
  • Form designer
  • Lots of icons and pictures for your use
  • Response to mouse and keyboard actions
  • Full array of Mathematical string handling and graphics functions
  • Create user interface using design tools
  • Add drawing to form
  • Set properties for the individual object on the form
  • Build an executable file
  • Useful debugger and error-handling facilities
  • Examine the objects in the forms
  • Work with data in programs (ODBC)
  • Add more functionality to the program by writing code
  • Can handle fixed and dynamic variable and control arrays
  • Powerful database access tools
  • New performance enhancements
  • ActiveX Technology


Advantages of Visual Basic
1.      Visual programming enables Visual development of GUI.
2.      One of the principal advantages is that the programmer need not write code to display the required component.
3.      The visual programming environment display a list of available methods and properties. The programmer picks up the required property available from the list.
4.      The component can be moved, resized and deleted.
5.      Saving the development Time.
6.      Increase the Productivity of the Program.

Disadvantages of Visual Basic
Development environment is highly graphical in nature and therefore requires more memory.
  1. Larger capacity hard disk is required.
  2. More RAM is required.
  3. Faster Processor is required.
  4. Visual development environment can be used only with GUI, such as the windows operating system.
  5. VB has no storage capacity. VB is front end tool so you cannot store any records. It simply displays the record stored in any backend tool.

OOPS Concept
Visual Basic 6.0 is an event driven programming language which has some of the elements of an object- oriented programming language, but not all of the features of an object oriented programming language.

The OOP model provides support for three basic principles:
1.      Encapsulation
2.      Polymorphism
3.      Inheritance

  1. Encapsulation means that the information about an object(its properties) and the processes  that are performed by the object(its method) are al l contained within the definition of the object. A real world example of an object is car. You describe a car by its properties, such as red convertible or a black four-door sedan. Each characteristics – color, number of doors, convertible, or hardtop-is a property of the car. As for the methods, these are the things that a car does in response  to an event.
For example, you initiate an event when you turn the key to start the car. The car’s “start method” takes over at that point, providing instructions such as “connect the starter gear, turn the starter, start fuel flow, initiate power to spark plugs, and disengage the starter.”

  1. Polymorphism means that many objects can have the same method and that the appropriate action is taken for the specific object calling the method. For example, in your programs, you display text to the screen and output to the printer. Each of these objects can have a print or display method that tells the object to place text in certain location. The method knows what to do, based on the object calling the method.
For example, you can specify Printer.Print, Form.Print, PictureBox.Print.  Printer.Print sends its output to the printer object, Form.Print sends output to the form, PictureBox.Print sends output to a picture box control.

  1. Inheritance means the ability to create a new class from an existing class. It means that one object can be based upon the description of another object. From the OOP purist point of view, VB doesn’t allow inheritance.
For example, in theory you should be able to create a new class called MyCheckBox based on the checkbox class. It would have all of the properties, methods, and events of checkboxes, but you would specify that shape of the checkbox is your company logo.

Explain VB Event.
While your project is being executed the user can do many things such as move the mouse around, click on either button, move, resize or close your forms window or jump to another application. Each action by the user causes an event to occur in your VB project. Some events(like clicking on a command button), you care about and some events like moving the mouse and resizing the window, you don’t care about. If you write basic code for a particular event then VB responds to the event and automatically execute your procedure. VB ignores event for which no procedures are written.

Explain VB event procedure
You write code in VB in procedures. For now each of your procedures will be a sub procedure which begins with the word “Private Sub” and ends with “End Sub”.
VB automatically names your event procedures. The name consists of the object name and underscore(_) and the name of the event.
Ex. The click event for your command button “cmdPush” will be “cmdPush_Click()”.
Explain Event Driven Programming
Events are the actions that are performed by the user during the application usage. If a user clicks a mouse button on any object then the Click event occurs. If a user moves the mouse, then the mousemove event occurs. By the same way an application can generate key down, key up event, mouse double click event.
The interface components have the ability to recognize user’s event. This code is built into the interface components. The response of the component to the event is decided by the program.
When an interface component is used, the programmer decides the action required of the component. In response to a particular event and right code that will be executed when the event occurs.
Example: In the calculator, the number button display the selected number in response to the mouse click while the button sqrt calculates and display the square root of the number.
Each interface component can have multiple events. In addition on interface component may also response to multiple event.
Example: A textbox can respond to a mouse click as well as key press event.
In event driven programming an application is built in a series of responses to the user event. The calculator is a good example of an application of event driven programming.
The code executed in response to an event is called the “Event Handler”.

Comments
·         Using (‘) single quotes (aphostrophee)
·         Using keyword REM

VB as an Event Driven Programming Language:
Visual Basic is event-driven, meaning code remains idle until called upon to
respond to some event (button pressing, menu selection, ...). Visual Basic is
governed by an event processor. Nothing happens until an event is detected.
Once an event is detected, the code corresponding to that event (event
procedure) is executed. Program control is then returned to the event processor.


In VB, the execution of the program takes when an event associated with the code happens like click event. Visual Basic’s flow of programming is determined by the events. Because until an event occurs the execution of the process will not be done.
For example, if you have a command button in your form, the following are all considered to be events of the command button: when user moves his mouse over the command button, when the user clicks on the command button.
In windows terminology, an event is the action that user takes. Whenever the user clicks the mouse, presses a key, responds to a control, or selects from a menu, an event happens. Windows constantly monitors the running Visual Basic program, looking for events.


VB AS IDE(Integrated Development Environment)
Visual basic environment (IDE)
When using Visual Basic, the most important skill you need to be adopt at using the development environment. Without the integrated tools in the environment, VB programming would be much more cumbersome and difficult. All design would need to be done on graph paper and flow charts, and it would need to be typed in line by line.
Fortunately, VB contains many integrated tools to make the application development process simpler. This collection of tools makes up the integrated development environment (IDE).

Six windows appear when you start Visual Basic.
The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options.
The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.



The Form Window is central to developing Visual Basic applications. It is where you draw your application.


The Toolbox is the selection menu for controls used in your application.
The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.




The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor’s screen:
The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.
As mentioned, the user interface is ‘drawn’ in the form window. There are two ways to place controls on a form:
1. Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize it.
2. Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn.
To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button.
To resize a control, click the object so that it is select and sizing handles appear.
Use these handles to resize the object.


Details of the icons on the toolbar




VB CONTROLS

The Form Object

The Form is where the user interface is drawn. It is central to the development of Visual Basic applications.

Form Properties:
Appearance - Selects 3-D or flat appearance.
BackColor - Sets the form background color.
BorderStyle - Sets the form border to be fixed or sizeable.
Caption - Sets the form window title.
Enabled - If True, allows the form to respond to mouse and keyboard events; if False, disables form.
Font - Sets font type, style, size.
ForeColor - Sets color of text or graphics.
            Picture  - Places a bitmap picture in the form.
Visible - If False, hides the form.

Form Events:
Activate - Form_Activate event is triggered when form becomes the active window.
Click - Form_Click event is triggered when user clicks on form.
DblClick - Form_DblClick event is triggered when user doubleclicks on form.
Load - Form_Load event occurs when form is loaded. This is a good place to initialize variables and set any runtime properties.

Form Methods:
            Cls - Clears all graphics and text from form. Does not clear any objects.
Print - Prints text string on the form.

Examples
frmExample.Cls ' clears the form
frmExample.Print "This will print on the form


Command Buttons

We've seen the command button before. It is probably the most widely used control. It is used to begin, interrupt, or end a particular process.

Command Button Properties:
            Appearance - Selects 3-D or flat appearance.
Cancel - Allows selection of button with Esc key (only one button on a form can have this property True).
Caption - String to be displayed on button.
Default - Allows selection of button with Enter key (only one button on a form can have this property True).
Font - Sets font type, style, size.
Picture - Returns or sets a graphic or picture to be displayed in a control.
Style - Returns or sets a value indicating the display type and behavior of the control. If you wish to use picture to be displayed on the command button you have to use Style property as 1 - Graphical. By default it is 0 - standard.

Command Button Events:
Click - Event triggered when button is selected either by clicking on it or by pressing the access key.
            DblClick- Event triggered when user double-clicks on a command button.
            MouseMove (Button as integer, Shift as integer, x as single, y as single)
Fires when user moves mouse over the text box.

Label Boxes
A label box is a control you use to display text that a user can't edit directly. We've seen, though, in previous examples, that the text of a label box can be changed at run-time in response to events.

Label Properties:
Alignment - Aligns caption within border.
Appearance - Selects 3-D or flat appearance.
AutoSize -If True, the label is resized to fit the text specified by the caption property. If False, the label will remain the size defined at design time and the text may be clipped.
BorderStyle - Determines type of border.
            Caption - String to be displayed in box.
Font - Sets font type, style, size.
BackStyle - 0 - Transparent, 1 - Opaque i.e. indicates background style for the label


Label Events:
Click- Event triggered when user clicks on a label.
DblClick- Event triggered when user double-clicks on a label.
MouseMove (Button as integer, Shift as integer, x as single, y as single)
Fires when user moves mouse over the text box.
Text Boxes

           
                                   

A text box is used to display information entered at design time, by a user at runtime, or assigned within code. The displayed text may be edited.

Text Box Properties:
            Appearance- Selects 3-D or flat appearance.
BorderStyle -Determines type of border.
Font- Sets font type, style, size.
MaxLength -Limits the length of displayed text (0 value indicates unlimited length).
MultiLine -Specifies whether text box displays single line or multiple lines.
PasswordChar- Hides text with a single character.
ScrollBars- Specifies type of displayed scroll bar(s).
Locked            -True / False i.e. If Text1.Locked = True then user can not edit the text of text box

Run time properties of textbox
SelLength- Length of selected text (run-time only).
SelStart- Starting position of selected text (run-time only).
SelText -Selected text (run-time only).Text Displayed text.

Text Box Events:

Change()- Triggered every time the Text property changes.

LostFocus() -Triggered when the user leaves the text box. This is a
good place to examine the contents of a text box after
editing.

KeyPress() - Triggered whenever a key is pressed. Used for key
trapping, as seen in last class.

GotFocus ( )- Fires when text box get cursor into it

MouseMove (Button as integer, Shift as integer, x as single, y as single)
Fires when user moves mouse over the text box.

Text Box Methods:

SetFocus- Places the cursor in a specified text box.
Example
txtExample.SetFocus ' moves cursor to box named txtExample

Check Boxes
                       

Check boxes provide a way to make choices from a list of potential candidates.
Some, all, or none of the choices in a group may be selected.

Check Box Properties:

Caption - Identifying text next to box.

Font -Sets font type, style, size.

Value- Indicates if unchecked (0, vbUnchecked), checked (1,vbChecked), or grayed out (2, vbGrayed).

Picture-Returns or sets a graphic or picture to be displayed in a control.

Style-Returns or sets a value indicating the display type and behavior of the control. If you wish to use picture to be displayed on the Check Box you have to use Style property as 1 - Graphical. By default it is 0 standard.


Check Box Events:

Click- Triggered when a box is clicked. Value property is automatically changed by Visual Basic.

Option Buttons

                                                                                 

Option buttons provide the capability to make a mutually exclusive choice among a group of potential candidate choices. Hence, option buttons work as a group, only one of which can have a True (or selected) value.

Option Button Properties:

Caption- Identifying text next to button.

Font -Sets font type, style, size.

Value- Indicates if selected (True) or not (False). Only oneoption button in a group can be True. One button in each group of option buttons should always be initialized to True at design time.

Picture-Returns or sets a graphic or picture to be displayed in a control.

Style-Returns or sets a value indicating the display type and behavior of the control. If you wish to use picture to be displayed on the optionbutton you have to use Style property as 1 - Graphical. By default it is 0 - standard.


Option Button Events:

Click -Triggered when a button is clicked. Value property is automatically changed by Visual Basic.

Frames

            

We've seen that both option buttons and check boxes work as a group. Frames
provide a way of grouping related controls on a form. And, in the case of option
buttons, frames affect how such buttons operate.
To group controls in a frame, you first draw the frame. Then, the associated
controls must be drawn in the frame. This allows you to move the frame and
controls together. And, once a control is drawn within a frame, it can be copied
and pasted to create a control array within that frame. To do this, first click on the
object you want to copy. Copy the object. Then, click on the frame. Paste the
object. You will be asked if you want to create a control array. Answer Yes.
Drawing the controls outside the frame and dragging them in, copying them into a
frame, or drawing the frame around existing controls will not result in a proper
grouping. It is perfectly acceptable to draw frames within other frames.
As mentioned, frames affect how option buttons work. Option buttons within a
frame work as a group, independently of option buttons in other frames. Option
buttons on the form, and not in frames, work as another independent group. That
is, the form is itself a frame by default. We'll see this in the next example.

It is important to note that an independent group of option buttons is defined by
physical location within frames, not according to naming convention. That is, a
control array of option buttons does not work as an independent group just
because it is a control array. It would only work as a group if it were the only group
of option buttons within a frame or on the form. So, remember physical location,
and physical location only, dictates independent operation of option button
groups.

Frame Properties:

Caption -Title information at top of frame.
Font -Sets font type, style, size.
BorderStyle- 0 – None,1 - Fixed Single
Visible- True / False. If True then Frame will not be visible while in run mode.




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

List Box Properties:

Appearance- Selects 3-D or flat appearance.

List -Array of items in list box.

ListCount- Number of items in list.

ListIndex- The number of the most recently selected item in list. If no item is selected, ListIndex= -1.

MultiSelect- Controls how items may be selected (0-no multipleselection allowed, 1-multiple selection allowed, 2-group selection allowed).

Selected- Array with elements set equal to True or False, depending on whether corresponding list item is selected.

Sorted- True means items are sorted in 'Ascii' order, else items appear in order added.

Text- Text of most recently selected item.

ItemData-Returns or sets a specific number for each item in a List Box control.

Style- 0 - Standard,1 – Checked.Returns or sets a value indicating the display type and behavior of the control. Read only at run time.


List Box Events:

Click - Event triggered when item in list is clicked.
DblClick- Event triggered when item in list is double-clicked. Primary way used to process selection.
Scroll -For a List Box control, this event occurs only when the scrollbars in the dropdown portion of the control are manipulated.

List Box Methods:

AddItem - Allows you to insert item in list.

Clear- Removes all items from list box.

RemoveItem- Removes item from list box, as identified by index of
item to remove.

Examples
lstExample.AddItem "This is an added item" ' adds text string to list
lstExample.Clear ' clears the list box
lstExample.RemoveItem 4 ' removes lstExample.List(4) from list box

Items in a list box are usually initialized in a Form_Load procedure. It's always a
good idea to Clear a list box before initializing it.
You've seen list boxes before. In the standard 'Open File' window, the Directory
box is a list box with MultiSelect equal to zero.

Combo Boxes
                                   

The combo box is similar to the list box. The differences are a combo box
includes a text box on top of a list box and only allows selection of one item. In
some cases, the user can type in an alternate response.

Combo Box Properties:

Combo box properties are nearly identical to those of the list box, with the deletion
of the MultiSelect property and the addition of a Style property.

Appearance -Selects 3-D or flat appearance.

List- Array of items in list box portion.

ListCount- Number of items in list.

ListIndex -The number of the most recently selected item in list. If no item is selected, ListIndex = -1.

Sorted -True means items are sorted in 'Ascii' order, else items appear in order added.

Style -Selects the combo box form.
Style = 0, Dropdown combo; user can change selection.
Style = 1, Simple combo; user can change selection.
Style = 2, Dropdown combo; user cannot change selection.

Text -Text of most recently selected item.

Combo Box Events:

Click- Event triggered when item in list is clicked.

DblClick- Event triggered when item in list is double-clicked. Primary way used to process selection.

Combo Box Methods:

AddItem- Allows you to insert item in list.

Clear- Removes all items from list box.

RemoveItem -Removes item from list box, as identified by index of item to remove.

Examples
cboExample.AddItem "This is an added item" ' adds text string to list
cboExample.Clear ' clears the combo box
cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box
You've seen combo boxes before. In the standard 'Open File' window, the File
Name box is a combo box of Style 2, while the Drive box is a combo box of Style 3.

Line Tool

                                   


The line tool creates simple straight line segments of various width and color.
Together with the shape tool discussed next, you can use this tool to 'dress up'
your application.

Line Tool Properties:

BorderColor -Determines the line color.

BorderStyle -Determines the line 'shape'. Lines can be transparent, solid, dashed, dotted, and
combinations.

BorderWidth- Determines line width.
There are no events or methods associated with the line tool.

Since the line tool lies in the middle-layer of the form display, any lines drawn will
be obscured by all controls except the shape tool or image box.


Shape Tool
           
                         

The shape tool can create circles, ovals, squares, rectangles, and rounded
squares and rectangles. Colors can be used and various fill patterns are
available.

Shape Tool Properties:

BackColor -Determines the background color of the shape (only
used when FillStyle not Solid.

BackStyle- Determines whether the background is transparent
or opaque.

BorderColor- Determines the color of the shape's outline.

BorderStyle -Determines the style of the shape's outline. The
border can be transparent, solid, dashed, dotted,
and combinations.
BorderWidth- Determines the width of the shape border line.

FillColor- Defines the interior color of the shape.

FillStyle -Determines the interior pattern of a shape. Some choices are: solid, transparent, cross, etc.

Shape- Determines whether the shape is a square, rectangle, circle, or some other choice.
Like the line tool, events and methods are not used with the shape tool.Shapes are covered by all objects except perhaps line tools and image boxes (depends on their Z-order) and printed or drawn information. This is a good feature in that you usually use shapes to contain a group of control objects and you'd want them to lie on top of the shape.

Horizontal and Vertical Scroll Bars
    
                                 *    

Horizontal and vertical scroll bars are widely used in Windows applications.
Scroll bars provide an intuitive way to move through a list of information and make
great input devices.
Both type of scroll bars are comprised of three areas that can be clicked, or
dragged, to change the scroll bar value. Those areas are:






Clicking an end arrow increments the scroll box a small amount, clicking the
bar area increments the scroll box a large amount, and dragging the scroll box
(thumb) provides continuous motion. Using the properties of scroll bars, we can
completely specify how one works. The scroll box position is the only output
information from a scroll bar.




Scroll Bar Properties:

LargeChange- Increment added to or subtracted from the scroll bar

Value- property when the bar area is clicked.

Max -The value of the horizontal scroll bar at the far right and the value of the vertical scroll bar at the bottom.Can range from -32,768 to 32,767.

Min- The other extreme value - the horizontal scroll bar at the left and the vertical scroll bar at the top. Can range from -32,768 to 32,767.

SmallChange- The increment added to or subtracted from the scrollbar Value property when either of the scroll arrows is clicked.

Value- The current position of the scroll box (thumb) withinthe scroll bar. If you set this in code, Visual Basic moves the scroll box to the proper position.










A couple of important notes about scroll bars:
1. Note that although the extreme values are called Min and Max, they do not
necessarily represent minimum and maximum values. There is nothing to
keep the Min value from being greater than the Max value. In fact, with vertical
scroll bars, this is the usual case. Visual Basic automatically adjusts the sign
on the SmallChange and LargeChange properties to insure proper
movement of the scroll box from one extreme to the other.

2. If you ever change the Value, Min, or Max properties in code, make sure
Value is at all times between Min and Max or and the program will stop with an
error message.


Scroll Bar Events:

Change- Event is triggered after the scroll box's position has been modified. Use this event to retrieve the Value property after any changes in the scroll bar.

Scroll- Event triggered continuously whenever the scroll box is being moved.

Picture Boxes
 
The picture box allows you to place graphics information on a form. It is best
suited for dynamic environments - for example, when doing animation.
Picture boxes lie in the top layer of the form display. They behave very much like
small forms within a form, possessing most of the same properties as a form.

Picture Box Properties:

AutoSize- If True, box adjusts its size to fit the displayed graphic.

Font -Sets the font size, style, and size of any printing done in the picture box.

Picture- Establishes the graphics file to display in the picturebox.

Picture Box Events:

Click -Triggered when a picture box is clicked.

DblClick- Triggered when a picture box is double-clicked.


Picture Box Methods:

Cls- Clears the picture box.

Print- Prints information to the picture box.

Examples
picExample.Cls ' clears the box picExample
picExample.Print "a picture box" ' prints text string to picture box

Picture Box LoadPicture Procedure:

An important function when using picture boxes is the LoadPicture procedure. It
is used to set the Picture property of a picture box at run-time.
Example
picExample.Picture = LoadPicture("c:\pix\sample.bmp")
This command loads the graphics file c:\pix\sample.bmp into the Picture property
of the picExample picture box. The argument in the LoadPicture function must be
a legal, complete path and file name, else your program will stop with an error
message.

Five types of graphics files can be loaded into a picture box:

Bitmap An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. Usually has a .bmp extension. Appears in original size.

Icon A special type of bitmap file of maximum 32 x 32 size.Has a .ico extension. We’ll create icon files in Class 5. Appears in original size.

Metafile A file that stores an image as a collection of graphical objects (lines, circles, polygons) rather than pixels. Metafiles preserve an image more accurately than bitmaps when resized. Has a .wmf extension.Resizes itself to fit the picture box area.

JPEG JPEG (Joint Photographic Experts Group) is a compressed bitmap format which supports 8 and 24 bit color. It is popular on the Internet. Has a .jpg extension and scales nicely.

GIF GIF (Graphic Interchange Format) is a compressed bitmap format originally developed by CompuServe.It supports up to 256 colors and is popular on the Internet. Has a .gif extension and scales nicely.




Image Boxes
                                   
An image box is very similar to a picture box in that it allows you to place
graphics information on a form. Image boxes are more suited for static situations
- that is, cases where no modifications will be done to the displayed graphics.

Image boxes appear in the middle-layer of form display, hence they could be
obscured by picture boxes and other objects. Image box graphics can be resized
by using the Stretch property.

Image Box Properties:

Picture- Establishes the graphics file to display in the imagebox.

Stretch- If False, the image box resizes itself to fit the graphic.If True, the graphic resizes to fit the control area.

Image Box Events:

Click- Triggered when a image box is clicked.

DblClick- Triggered when a image box is double-clicked.

The image box does not support any methods, however it does use the
LoadPicture function. It is used in exactly the same manner as the picture box
uses it. And image boxes can load the same file types: bitmap (.bmp), icon
(.ico), metafiles (.wmf), GIF files (.gif), and JPEG files (.jpg). With Stretch = True,
all three graphic types will expand to fit the image box area.

Drive List Box
 
The drive list box control allows a user to select a valid disk drive at run-time. It
displays the available drives in a drop-down combo box. No code is needed to
load a drive list box; Visual Basic does this for us. We use the box to get the
current drive identification.

Drive List Box Properties:

Drive- Contains the name of the currently selected drive.

Drive List Box Events:

Change- Triggered whenever the user or program changes the drive selection.


Directory List Box

                                   
The directory list box displays an ordered, hierarchical list of the user's disk directories and subdirectories. The directory structure is displayed in a list box.
Like, the drive list box, little coding is needed to use the directory list box – Visual Basic does most of the work for us.
Directory List Box Properties:

Path- Contains the current directory path.

Directory List Box Events:

Change- Triggered when the directory selection is changed.
                  
File List Box
                                               

The file list box locates and lists files in the directory specified by its Path
property at run-time. You may select the types of files you want to display in the
file list box

File List Box Properties:

FileName- Contains the currently selected file name.

Path- Contains the current path directory.

Pattern- Contains a string that determines which files will be displayed. It supports the use of * and ? wildcard characters. For example, using *.dat only displays files with the .dat extension.

File List Box Events:

DblClick- Triggered whenever a file name is double-clicked.

PathChange- Triggered whenever the path changes in a file list box.

You can also use the MultiSelect property of the file list box to allow multiple file Selection


Steps for building a Visual Basic Application

After designing the application, for building an application in Visual Basic following
steps are to be taken :

1. Draw the Interface
Create the form and the various objects on the form using toolbox.

2. Set the Properties
Set the properties of the various objects on the form with the help of properties
window.

3. Write the events code
In the code window, write the code associated with each object on the form and then
run the application

_ Few Examples to start with Visual basic

_ How to Start a project
_ Start the visual basic by clicking

Start>>Programs>>Microsoft Visual Studio
6.0>>Microsoft Visual Basic
_ Choose Standard EXE from the available screen
_ Click Open.
_ A blank form will appear on the screen with Project Explorer Window, Properties
Window and Tool Box .


Example 1: This example is to print a text in the text box by clicking on the button.
With the help of Tool Box given on the left side of the interface, draw the following
interface :



_ Set the properties of the objects on the form as given in the table below :

_ Double click First Command Button and write the following lines of code
Private Sub Command1_Click()
Text1.Text = "Welcome to Visual Basic"
End Sub
_ Click View Object to come back at the form
_ Double click Second Command Button and write the following lines of code
Private Sub Command2_Click()
End
End Sub
_ Run the project by clicking Run>>Start or Press F5.
_ Save the project by clicking File>>Save Project.
_ Specify the folder in which all the files like form, reports etc. related with the project
along with the project name are to be saved.


Few Definitions to remember

Few technical terms that will be used in the development of Visual Basic Project very
often :

Controls - Reusable objects that provide the pieces of the visual interface of a program. Examples of controls are a text box, a label, or a command button.

Event- An  action initiated by the user, the operating system, or the program itself.
Examples of events are a keystroke, a mouse click, the expiration of a specified
amount of time, or the receipt of data from a port.

Methods -  Predefined actions that can be performed by an object. For example, a form has a Hide method that makes it invisible to the user.

Object - A basic element of a program, which contains properties to define its characteristics, contains methods to define its tasks, and recognizes events to which
it can respond. Controls and forms are examples of the objects used in Visual Basic.

Procedures- Segments of code that you write to accomplish a task. Procedures are often written to respond to a specific event. Types of procedures include Subprocedures, which consist of a sequence of statements; and Functions, which return a value.

Properties  - The characteristics of an object, such as its size, position, color, or text font.
Properties determine the appearance and sometimes the behavior of an object. Properties are also used to provide data to an object and to retrieve information from the object.


ADVANCE CONTROLS
In VB We have some other control then intrinsic controls. We can add new ActiveX control on toolbox by selecting component option form project menu or using shortcut key(Ctrl+T) or right clicking on toolbox. Some of the most commonly used ActiveX controls are as follows:
·         Common Dialog Box Control
·         Rich Text Box Control
·         MSFlex Grid Control





  Common Dialog Control:
                                                                 
   The Common Dialog Box control provides a standard set of dialog boxes for operations such as opening and saving files, setting print options, and selecting colors and fonts.

       The control also has the ability to display help by running the Windows Help engine.
The CommonDialog control provides an easy and convenient way to invoke
the Color, Font, Printer, FileOpen, and FileSave Windows common dialog
boxes.
This control exposes only properties and methods—no events.

 The control is invisible during the execution, so it doesn't support properties such as Left, Visible, or TabIndex.

This control is embedded in the ComDlg32.ocx file, which has to be distributed with any Visual Basic application that uses it.

Following figure shows OCX control name and also shows control in Toolbar
(Last Control)


         You use the Common Dialog control in ur application by adding it to a form and setting its properties. The dialog displayed by the control is determined by the methods of the control. At run time, a dialog box is displayed or the help engine is executed, when the appropriate method is invoked; at design time, the Common Dialog Box control is displayed as an icon on a form.

   Common Dialog control can display the following dialogs using the specified method.
      Method
        Dialog Displayed
ShowOpen
Show Open Dialog Box
ShowSave
Show Save As Dialog Box
ShowFont
Show Font Dialog Box
Show Printer
Show Print or Print Options Dialog Box
Show Color
Show Color Dialog Box
ShowHelp
Invokes the Window Help Engine

Ø     Open DialogBox

The Open Dialog box allows the user to specify a drive, a directory, a file name extension, and a file name.
Syntax: Controlname.methodname
Ex: CommonDialog1.ShowOpen

                                                  

 Properties of Open Dialog Box

1. CancelError: If true, generates an error if the  Cancel button is clicked. Allows you to use error handling procedures to recognize that Cancel was clicked.

2. DialogTitle: The string appearing in the title bar of the dialog box. Default is Open. In the example, the DialogTitle is Open Example.

3. FileName :Sets the initial file name that appears in the File name box. After the dialog box   is closed, this property can be read to  determine the name of the selected file.

       4. Filter:   Used to restrict the filenames that appear in the filelist box. Complete     filter specifications for forming a Filter can be found using on-line help. In the example, the Filter was set to allow Bitmap (*.bmp), Icon (*.ico), Metafile (*.wmf), GIF (*.gif), and JPEG (*.jpg) types (only the Bitmap choice is seen).
    
       5. Flags: Values that control special features of the Open dialog Box.                   


Save  Dialog Box

The Save As dialog box is identical to the Open dialog in appearance, except for the dialog’s caption, and file names appearing dimmed out.
At run time, when the user chooses a file and closes the dialog box, FileName property is used to get the selected file name.

  Syntax: Controlname.methodname
Ex: CommonDialog1.ShowSave




Properties of Save Dialog Box

1. CancelError -If True, generates an error if the Cancel button is clicked. Allows you to use error-handling procedures to recognize that Cancel was clicked.

2. DefaultExt -Sets the default extension of a file name if a file is listed without an extension.

3. DialogTitle- The string appearing in the title bar of the dialog box. Default is Save As. In the example, the DialogTitle is Save As Example.

4. FileName -Sets the initial file name that appears in the File name box. After the dialog box is closed, this property can be read to determine the name of the selected file.

5. Filter- Used to restrict the filenames that appear in the file list box.

6. FilterIndex- Indicates which filter component is default.

7. Flags -Values that control special features of the dialog box


Ø  Color Dialog Box

The Color Dialog Box allows the user to select a color from a palette or to create and select a custom color. At run time, when the user chooses a color and closes the dialog box, you use the Color property to get the selected color.

  Syntax: Controlname.methodname
Ex: CommonDialog1.flags=cdlCCFullOpen
      CommonDialog1.ShowColor




Properties of Color Dialog Box

1. Color: This property is useful to set initial selected color of dialog box. After the  dialog box is closed, this property can be read to determine the selected color.

2.  Flags: Values that control special features of the dialog box.

3. CancelError: If true, generates an error if the Cancel button is clicked. Allows you  to use error-handling procedures to recognize that Cancel was clicked.


Ø  Font Dialog Box

The Font Dialog box allows the user to select a font by its size, color and style. Once the user makes selection in the Font dialog box, the following properties contain information about the user’s selection.

Syntax: Controlname.methodname
Ex: CommonDialog1.flags=cdlCFScreenFonts
      CommonDialog1.ShowFont



Properties of Font Dialog Box

1. FontName: This property is useful to set initial selected font of dialog box. After the dialog box is closed, this property can be read to determine the selected font.

2. FontSize: This property is useful to set initial selected font size of dialog box. After the dialog box is closed, this property can be read to determine the selected font size.

3. FontBold: This property is useful to set initial font bold style of dialog box. After the dialog box is closed, this property can be read to determine the selected font bold style.

4. FontItalic: This property is useful to set initial font italic  style of dialog box. After the dialog box is closed, this property can be read to determine the selected font italic style.

5. FontUnderline: This property is useful to set initial font underline style of dialog box. After the dialog box is closed, this property can be read to determine the selected font underline style.

6. FontStrikethru: This property is useful to set initial font striketrhu style of dialog box. After the dialog box is closed, this property can be read to determine the selected font strikethru style.

7. Flags: Values that control special features of the dialog box.

8. CancelError: If True, generates an error if the cancel button is clicked. Allows you to use error-handling procedures to recognize that cancel was clicked.

Print Dialog Box

The Print dialog box allows the user to specify how output should be printed. The user can specify a range of pages to be printed, a print quality, a number of copies, and so on. This dialog box also displays information about the currently installed printer and allows the user to configure or reinstall a new default printer.

  Syntax: Controlname.methodname
Ex: CommonDialog1.ShowPrinter




Properties of Printer Dialog Box

1. Copies: This property is useful to set initial number of copies. After the dialog box is closed, this property can be read to determine the number of copies.

2. FromPage: This property is useful to set print starting page.

3.ToPage: This property is useful to set ending page.

4. Min: This property is useful to set minimum page number. Now user can enter in from and to page.

5. Max: This property is useful to set maximum page number. Now user can enter in from and to page.



2. MSFlex Grid Control

  The Microsoft FlexGrid(MSFlexGrid) control displays and operates on tabular data.

It allows complete flexibility to sort, merge, and format tables containing strings and pictures.

When bound to Data control, MSFlexGrid displays read-only data.

This control is loaded by selecting Microsoft MSFlexGrid Control 6.0
From the components dialog box.

Properties:

Rows: This property is useful to set number of rows in flexgrid control.

Cols: This property is useful to set number of columns in flexgrid control.

FixedRows: This property is useful to set fixed rows in flexgrid control.

FixedCols: This property is useful to set fixed columns in flexgrid control.

Row: This property is useful to get current selected row in flexgrid control(runtime)

Col: This property is useful to get current selected column in flexgrid control(runtime)

Text: This property is useful to set or get text of currently selected cell.



Some other property for formatting cell of Flexgrid are:

CellAlignment
CellForecolor
CellBackColor
CellFontBold
CellFontItalic
CellFontName
CellFontSize
CellFontStrike
CellFontUnderline

Methods:

1. AddItem(): This method is useful to add rows in flexgrid.

    Syntax: object.AddItem(string,index)
    String is item to add. While index is positioned where it will inserted.

2. RemoveItem(): This method is useful to remove rows in flexgrid.

    Syntax: object.RemoveItem(index,number)
    Index is index of row to delete. While number is how many row may              be deleted.

3. Clear(): This method is useful to clear contents of flexgrid.

    Syntax: object.clear()


3. RichTextBox Control

    The rich textbox control allows the user to enter and edit text, providing more advanced formatting features than the conventional textbox control.

The RichTextBox control is one of the most powerful controls provided with Visual Basic.

In a nutshell, it's a text box that's able to display text stored in Rich Text Format (RTF), a standard format recognized by virtually all word processors, including Microsoft WordPad (not surprisingly, since WordPad internally uses the RichTextBox control).

You can use different fonts for different text sections.

You can even control indents, hanging indents, and bulleted paragraphs.

This control is loaded by selecting the Microsoft Rich Textbox Control 6.0 from the components dialog box.

 It is used to implement a full featured text editor into any applications.

This control supports multiple font and colors, left and right margins,   bulleted lists, and more.

Properties of RichTextbox

1. FileName: It is used to load the contents of a .txt or .rtf file into the control.

RichTextBox have some text formatting property that is only available at run time.
SelFontName
SelFontSize
SelBold
SelItalic
SelUnderline
SelBullet
SelAlignment
SelStrikeThru
SelFontColor

These all the properties are useful to set fonttype, color and size and style

Methods of RichTextBox

1. LoadFile(): This method is useful to load file into RichTextBox

    Syntax: Controlname.LoadFile filename,filetype

     Where filename may be any valid filename path for existing file and filetype may be the following :

RtfRTF-(Default) RTF. The file loaded must be a valid .rtf file.

rtfText-Text. The RichTextbox control loads any text file

ex: RichTextbox1.LoadFile( “c:\data.txt”),rtfText                                       

When loading a file with the LoadFile method, the contents of the loaded file replaces the entire contents of the RichTextBox control.

2. SaveFile(): This method is useful to save contents of RichTextbox to a file.

Syntax: Controlname.SaveFile filename,filetype

Where filename may any valid filename path for existing file and file type may be the following.

RtfRTF-(Default) RTF. The file loaded must be a valid .rtf file.

rtfText-Text. The RichTextbox control loads any text file

Ex:Richtextbox1.SaveFile(“c:\data.txt”),rtfText

When using the savefile method all the contents written in the richtextbox control will be saved in the text file named data.txt

3. Span(): This method is useful to select the text in RichtextBox based on specified set of character.

Syntax: controlname.Span(characterset)

Here characterset is character or string to be selected.

Ex:Richtextbox1.Text=”Hello Good Morning”

    RichTextbox1.Span(“Good”)
    RichTextbox1.Selunderline=True

4. Find(): This method is useful to find the text in RichTextBox

   Syntax: controlname.Find(string,start,end)
Here string is string to find in RichTextbox while

start is an integer value to specify from where to find in RichTextbox

While end is position where to end the search.






Message Box

The MsgBox function uses the following syntax:

MsgBox( prompt [, buttons] [, title] [, helpFile, context] )

The arguments for the MsgBox function are described in the following table.
Argument Description
prompt -Text that contains message to the user.
buttons -Determines the number of and type of message box buttons as well as the type of symbol that appears on the message box.For more information about using MsgBox function constants, search for "MsgBox arguments" in MSDN Help.
Title- The text that appears in the title bar of the message box.

Note : Any arguments not enclosed in square brackets are required. You must supply a value for these arguments. Arguments that are enclosed in brackets are optional. If values are not supplied for these arguments, Visual Basic will use the default value. The following illustration shows a simple message box that is generated by the MsgBox function.


Fig. 1 can be generated with the statement given below.
MsgBox "This illustration shows a simple message box that is generated by
the MsgBox function.",vbOkOnly + vbInformation, "eBookMark"
MsgBox ( ) constants
Constant                                 Value                                      Description
vbOkOnly                                0                                 Display OK button only
vbOkCancel                             1                                  Display OK and Cancel buttons
vbAbortRetryIgnore                2                                  Display Abort, Retry and Ignore buttons
vbYesNoCancel                       3                                 Display Yes, No and Cancel buttons
vbYesNo                                  4                                  Display Yes and No Buttons
vbRetryCancel                         5                                 Display Retry and Cancel Buttons
vbCritical                                 16                                Display critical message icon
vbQuestion                              32                                Display Warning Query icon
vbExclamation                        48                                Display warning message icon
vbInformation                         64                                Display information Message icon


 Input Box()
Input boxes are an easy way for you to ask the user for input that can't be answered simply by clicking a button.
Following illustration shows input box that expects one input from user.

Fig. 1 can be created by using example stated below
MyValue = InputBox ("This illustration shows Input box that is generated by the Input Box function.", "eBookMark", "Default Value")

below is a syntax for input box :

InputBox( prompt[, title] [, default] [, xPos] [, yPos] [, helpFile, context] )

Note: For user input that requires no more than clicking a button, use the MsgBox function. When using the InputBox function, there is little control over the components of the dialog box. Only the text in the title bar, the command prompt displayed to the user, the position of the dialog box on the screen, and whether or not the dialog box displays a Help button can be changed. The MsgBox function provides more control over the appearance of the dialog box.

1 comments: