Software Notes by softsys

Search   Chat 


Visual Basic

Part - II

Controls
Visual basic 6.0 provides us with a number of Custom Controls. Some of them are data bound controls and some are Active X controls. Since a majority of these controls happen to be Active X Controls, these custom controls are also called as active X controls. An Active X control is an object that we place on a form to enable or enhance a user's interaction with an application. Active X controls have events and can be incorporated into other controls. These controls have a .ocx file name extension.

A custom control is an extension of the Visual Basic Toolbox. A custom control file is a special form of a dynamic link library file that contains one or more type of controls. When a custom control is added to the program it becomes part of the development and run-time environment and provides new functionality for the application.

More Active X Controls
SysInfo Control

This control can be used to detect systems events such as desktop resizing, resolution changes, time changes, or changes in platform, operating systems etc.

Microsoft SysInfo Control 6.0
Have a SysInfo Control on form. Write following code
Go to control panel and try to change time through Date/time option

Private Sub SysInfo1_TimeChanged()
MsgBox "Change in system time settings"
End Sub

Progress Bar Control
Components - Windows common control 6.0
Draw progress bar, command button and timer on form

Private Sub cmd_status_Click()
pb1.Value = 0
Timer1.Enabled = True
End Sub

Private Sub Form_Load()
Timer1.Enabled = False
pb1.Value = 0
End Sub

Private Sub Timer1_Timer()
pb1.Value = pb1.Value + 10
If pb1.Value >= 100 Then Timer1.Enabled = False
End Sub
Date time picker
U can use arrow keys to change values from DTpicker
Right click on control to set properties
Important property is Format

Private Sub dtp1_Click()
'Text1.Text = dtp1.Day
'Text1.Text = dtp1.DayOfWeek
'Text1.Text = dtp1.Hour
'Text1.Text = dtp1.Minute
'Text1.Text = dtp1.Month
'Text1.Text = dtp1.Second
End Sub

Flat Scroll Bar - Similar to Normal scroll bar or Slider
Private Sub fsb1_Change()
Text1.Text = fsb1.Value
End Sub

Microsoft windows common control 2
Image combo, Animation, Updown, monthview, Datepicket, Flatscrollbar
Right click on monthview control and set properties
U can have UpDown control and set its properties for monthview control

Treeview Control
This control is designed to display data that is hierarchical in nature, such as organisation trees, the entries in an index, the files and directories on a disk. It is often used in conjunction with a list view control, which is used to display the contents of the folder selected in the tree view.

List view control
It displays data as listitem objects. Each listitem object can have an optional icon associated with the label of the object. The control excels at representing subsets of data (such as members of the database) or discrete objects 9such as document templantes). The list view property is often used in association with a tree view control.

Image list control
An imagelist control contains a collection of images that can be used by other windows common controls.

Status Bar Control
It is a frame that can consist of several panels, which inform the user about the status of an application. The control can hold up to sixteen frames. Additionally, the control has a "Simple" style (set with the style property), that switches from multipanels to a single panel for special messages. The statusBar control can be placed at the top, bottom, or sides of an application. Optionally, the control can float within the application's client area.


Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
'Text1.Text = MonthView1.Day
'Text1.Text = MonthView1.DayOfWeek 'Sunday =1
'Text1.Text = MonthView1.MaxDate
'Text1.Text = MonthView1.MinDate
'Text1.Text = MonthView1.Month
'Text1.Text = MonthView1.Week
'Text1.Text = MonthView1.Year
End Sub

MsChart
Private Sub Form_Load()
Dim x(1 To 3, 1 To 4) As Variant
x(1, 2) = "NMV"
x(1, 3) = "NES"
x(1, 4) = "SSPMS"

x(2, 1) = "Year 1997"
x(2, 2) = 50
x(2, 3) = 68
x(2, 4) = 77

x(3, 1) = "Year 1998"
x(3, 2) = 70
x(3, 3) = 79
x(3, 4) = 80

MSChart1.ChartData = x
End Sub


Common Dialog Control
'Common dialog control is used to activate the built in dialog boxes provided by windows

'Sample 1

cd1.ShowColor
cd1.ShowOpen
cd1.ShowFont
cd1.ShowHelp
cd1.ShowPrinter
cd1.ShowSave

'Sample 2
'cd1.Action = 1 Open
'cd1.Action = 2 Save
'cd1.Action = 3 Font
'cd1.Action = 4 Color
'cd1.Action = 5 Print


Label1.Caption = cd1.FileName 'Assumption cd1.showopen
Form1.BackColor = cd1.Color 'Assumption cd1.showcolor


Toolbar Control
A toolbar control contains a collection of Button objects used to create a toolbar that can be associated with an application. Typically, a toolbar contains buttons that correspond to items in an application's menu, providing a graphic interface for the user to access an application's most frequently used functions and commands.

TabStrip Control
A TabStrip control acts like the dividers in a notebook or the labels on a group of file folders. By using a Tabstrip control, we can define multiple pages for the same area of a window or dialog box in our application. The Tabstrip control consists of one or more Tab objects in a tabs collection.

Slider Control
A slider control consists of a scale, defined by the min and max properties, and a "Thumb" which the end user can manipulate using the mouse or arrow keys.

Progress Bar Control
A Progress Bar is a Control, which allows us to graphically represent the progress of a transaction. The control consists of a frame that is filled as the transaction occurs. The value property determines how much of the control has been filled. The min and max properties set the limits of the control.

Updown Control
It is a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in a buddy control.

MonthView Control and DateTimePicker Control
A month view control displays the current month and lets the user scroll through other months as well. The day, month and year can be displayed using the monthview control.
The DateTimePicker control allows the user to specify a date or time. DateTimePickers can display a Monthview as a drop-down control, or the current time with an updown control to let the user select the time required.

MS Chart Control
Is associated with a data grid (data grid object). This data grid is a table that holds the data being charted.

Communication control
It allows us to add both simple serial port communication functionality to our application and advanced functionality to create a full-feateured, event driven communications tool. It provides an interface to a standard set of communication commands and also allows us to establish a connection to a serial port, connect to another communication device (a modem, for instance), issue commands and exchange data etc. It also monitors and respond to various events and errors that may be encountered during a serial connection.

Animation control
It displays only that Audio Video interleaved (AVI) files that have no sound. An AVI clip is a series of bitmap frames like a movie. One example is the piece of paper that flies between folders when copying files in the Windows 95 system. Only silent avi clips can be used with animation controls. At run time the animation control does not have a visible frame. The animation control maintains a separate thread of execution while it is playing. Therefore our application will not be blocked, and can continue to execute within its process.

'MicroSoft Windows Common Control -2 6.0
'Annimation Control
'1. Take Control and Command Button
'2. You can take Timer to close the Animation Effect

Private Sub Command1_Click()
Animation1.AutoPlay = True
Animation1.Open "C:\Program Files\Microsoft Visual Studio\Common\Graphics\Videos\filecopy.avi"
End Sub

Multimedia control
The multimedia control allows us to manage Media control interface (MCI) devices. These devices include soundboards, MIDI sequencers, CD-ROM drives, audio players, videodisc players, and videotape recorders and players. This multimedia control contains a set of push buttons that issue MCI commands, which resembles the commands (functions) we would expect to see on a typical compact disc player or videotape recorder.


Multimedia Control - Video Player
'Take Multimedia Control as mm and Picture Box as Picture1
'Set Properties DeviceType - AVIVideo
'Filename :-
D:\MicrosoftVisualStudio\VIntDev98\Samples\Gallery\content\mmedia\Globe.avi

Private Sub Form_Load()
mm.Command = "open"
mm.hWndDisplay = Picture1.hWnd
End Sub

Multimedia Control - Wave Audio
'Take Multimedia Control
'Set Properties DeviceType - WaveAudio
'File name - Any thing from d:\songs

Private Sub Form_Load()
mmccd.Command = "open"
End Sub


Internet Transfer Control
It implements two widely used Internet protocols: the Hypertext Transfer Protocol (HTTP) and the File Transfer Protocol (FTP). Using the Internet transfer control, we can connect to any site that uses one of these protocols, and retrieve files using either the opener or execute method.
Uses of Internet transfer control
1. Add an FTP browser to any application
2. Create an application that automatically downloads files from a public FTP site.
3. Parse a World Wide Web site for graphics references and download the graphics
4. Present a custom display of dynamic data retrieved from a web page.
MAPI Custom Controls
The messageing application program interface (MAPI) controls allow to create a mail enabled visual basic MAPI application. There are two MAPI custom controls. MAPI session and MAPI messages. The MAPI session control establishes a MAPI session, and then the MAPI messages control allows the user to perform a variety of messaging system function.

Masked Edit control
It provides restricted dat input as well as formatted data output. This control supplies visual cues about the type of data being entered or displayed. This is what the control looks like as an icon in the toolbox. For e.g. to allow the user to enter only data values the mask can be set to ****.

Picture Clip Control
It allows selecting an area of a source bitmap and then displaying the image of that area in a form or picture box. Picture clip controls are invisible at run time. This is a typical bitmap that might be used in the picture clip control.

Calendar Control
Text1.Text = Calendar1.Day & " " & Calendar1.Month & " " & Calendar1.Year
Text1.Text = Format(Calendar1.Value, "dddd, mmmm d yyyy")

Flex Grid Control

Rich Text Box Control

Tab Strip

Tool Bar - Image List

Status Bar


Components - Insertable Objects
Image Document
Media Clip
Microsoft Map

Form Templates
From form1 call these template forms - Use menu
1. Login Dialog (Password = password)
2. About
3. Splash Screen
4. Tip of the day (Create tipofday.txt in notepad - store this file in your application's directory.)

System Objects
App
Print App.EXEName
Print App.Path
Print App.Title

ClipBoard

Debug
Debug.Print "India"

Err

Printer
Print "Device Name : " & Printer.DeviceName
Print "Copies : " & Printer.Copies
Print "Driver Name : " & Printer.DriverName
Print "Page : " & Printer.Page
Print "Paper Size : " & Printer.PaperSize
Print "Print Quality: " & Printer.PrintQuality

Screen
Print Screen.MouseIcon
Print Screen.MousePointer
Print Screen.Width

User defined datatypes - Similar to structures in C
'A type statemetn is used to define a user defined type in the eneral declaration section of a form or module. User defined datatypes can only be private in form while in stadard modules can be public or private.

Private Type productdetails
prodid As String
prodname As String
price As Currency
End Type

Dim electronicgoods As productdetails 'Defined one record of above structure.
Dim electronicgoods(10) As productdetails ' Defines an array of 11 records.

A user defined type can be referenced in an application by using the variable name in the procedure along with the item name in the type block.

Text1.Text=electonicgoods.prodname

If the same is implemented as an array, then the statement becomes

Text1.Text=electonicgoods(1).prodname




Database Handling in VB
Access - Data Control (OldVb - addmoddel.vbp)
Access - DAO (OldVb - DAO Directory)
Access - ADO (ADO Control AMD.vbp)

Oracle - DAO - ODBCProject.vbp
Oracle - ADO (OLEDB - ADODC) AdoOdbc.vbp
Oracle - ADO - Connection (ADOAMD.vbp)
Oracle - DSN - ODBCProject.vbp

RDO - ODBCRDO.vbp
RDOAddModDel.vbp

DBBuilder
DBViewer

Database handling using Classes

Objects & Classes
An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application like control or a form. The entire application can be an object.
A class defines each object in VB. A class is usually described as the template from which an instance i.e. an object can be created. Class is used to define the characteristics of an object for instance, its size shape color etc. When we create an object from the class, we have in fact created an instance of the class. e.g. An individual form is an instance of the Forms Class.

OOPs Concepts
Encapsulation :-
Inheritance :-
Polymorphism :-

Object Variables
Special object type variables are used for working with objects. The scope of the object variable is given with Dim Private Public Static etc.
Dim frmvar as Form
Dim txtnewvar as TextBox
Public cmdnew as CommandButton
Private optnew as OptionButton

Set
When we want to make an object variable refer to a specific object of that type in our project, the SET keyword is used. Say our project has a form named form1 and textbox named text1, then the code will be
Dim textA as textbox
Set textA = text1

"New" Keyword
Used to crate a new instance of a visual basic object at run time is when we use an existing form as the class.
Dim frmform as New form1

Creates a new instance frmform of form1

Example

General_Declarations()
Dim frmaform As Form
Dim frmbform As Form

Private Sub Command1_Click()
Dim frmaform As New Form1
Dim frmbform As New Form1
frmaform.Show
frmbform.Show
End Sub

Working with objects
Visual basic objects support properties, methods, and events. In VB setting the attributes of an object are referred to as properties, while the various procedures that can operate on the object are called its methods. An event is an action recognized by an object such as click, mousemove, keypress etc.

Example

Object : TV

Property : Contrast
TV.Contrast=75

Method : Dial
Phone.Dial 4210891

Event : TV = ContrastChange, Phone = Ring.

Setting Property values
Object.property = expression

Getting property values
Variable = object.property

Methods are of two types
Methods without argument : Combo1.Additem Data1.Refresh
Methods with argument : Circle(1000,1000),20

Constructors and Destructors
When we use the New operator to create an object, visual basic automatically allocates the space it needs for object's data members. We can write any other initialization code in the constructor if we need to. Common operations for constructors are
Assigning default properties
Asking the user for additional data

The role of destructors is to free the space allocated for the constructor. VB automatically frees the space once the object is destroyed.


Collection
When related objects are grouped in VB, a collection is created. Collections are of many types. Collections are sometimes created automatically when forms or controls are added to an application. They can also be created by creating a collection object. For example : if multiple instances of the form is created using the Dim statement with the New keyword, a forms collection is created.

Collection object
A collection object is an ordered set of items that can be considered as a unit. The items in the collection can be of any data type hence by default the type of the item is variant. The properties and methods of collection are …

Method Description
Add Add items to the collection
Remove Removes items from the collection
Count Returns the number of items in the collection
Item Returns an item referenced by index property

Working with object variables
Object variables are similar to pointers. The coding can be reduced by using these object variables and is thus simplified. The set statement is used to associate a particular control with an object variable.

Example

Private Sub Form_Load()
Dim cmb As ComboBox
Set cmb = Form1.cmbname
cmb.AddItem "Type"
cmb.AddItem "Gifts"

'The same can be extended to form an array of object variables as given below
Dim txt(3) As TextBox
'In the form load even following code is included
Set txt(1) = txtname
Set txt(2) = txtaddress
Set txt(3) = txtage

'To perform opetations with all text boxes
For a = 1 To 3
txt(a).Visible = True
Next a

End Sub


Classes and Class Modules
Classes can be built by adding custom properties to a form and then used as templates for new objects. The most common way in VB is to build Class Module. A class module object contains the code for the custom properties and methods that objects defined. Any number of class modules can be created in a project. Each class module created will give us a single class (template) to build new instances of that class.

Example : How class module can be used to define classes that can be used to create objects. It also describes the procedure to create properties and methods for the new class. How object can be constructed and destroyed.

Project Steps
1. Project --' Add class Module
2. Add four command buttons to form
3. Set following properties

Object Property Setting
Class Module Name Thing
Command 1 Caption Show the thing
Command 2 Caption Reverse the things name
Command 3 Caption Create the new thing
Command 4 Caption Temporary thing

4. Add code to class module
5. Add code to form

Code to be added in class module
Option Explicit
Public Name As String
Private mdtmCreated As Date

' The variable "Name" will be the property of the Thing object as it is declared public so always declare properties Public
' The mdtmCreated is a private data member that is used to store the value of the read-only created property. The created property returns the date and time a Thing object was created.

Property Get Created() As Date
Created = mdtmCreated
End Property

Public Sub ReverseName()
'The thing object has one method, ReverseName, which simply reverses the order of the lettrs in the name Property. It does not return a value, hance it is implemented as procedure
Dim intCt As Integer
Dim strNew As String
For intCt = 1 To Len(strNew)
strNew = Mid$(strNew, intCt, 1) & strNew
Next
Name = strNew
End Sub

Private Sub Class_Initialize()
'Initialize event gets executed, moment the object is created
'Class modules have two events, initialise and terminate.
mdtmCreated = Now 'display object properties
MsgBox "name : " & Name & vbCrLf & "Created : " & Created, , "Thing Initialise"
End Sub

Private Sub Class_Terminate()
'Terminate event contains any code that is needed to execute in order to clean up after the object when it is being destroyed.
MsgBox "name : " & Name & vbCrLf & "Created : " & Created, , "Thing Terminate"
End Sub

Class module code end


Code to be added for the form
'Using the thing object
Option Explicit
Private mth As thing ' The variable mth will pointer to a thing object which will be created in the forms load event.

Private Sub Command1_Click()
MsgBox "Name : " & mth.Name & vbCrLf & "Created :" & mth.Created, , "Form Thing"
End Sub

Private Sub Command2_Click()
mth.ReverseName
Command1.Value = True
End Sub

Private Sub Command3_Click()
Set mth = New thing
mth.Name = InputBox("Enter the name for the new thing")
End Sub

Private Sub Command4_Click()
Dim thTemp As New thing
thTemp.Name = InputBox("enter a name for the temporary thing")
End Sub

Private Sub Form_Load()
Set mth = New thing
mth.Name = InputBox("Enter the name for the thing")
End Sub

Form code End


Accessing oracle Database using Remote Data Control
Steps
=====
1. Right click on toolbox -- go to components -- and select
Microsoft remote data contro 6.0
Databound grid control.
2. Take both the controls on form
3. right click on remote data control and set properties
4. datasource name = dsn name i.e. Umesh
5. username : scott
6. password : tiger
7. sql = select * from dept
8. set datasource property of dbgrid to MSRDC1 - microsoft remote data control.
9. Run the project - F5

End - Accessing oracle Database using Remote Data Control


DragDrop Event
'Set DragMode property for both the pictures = automatic
Private Sub Picture3_DragDrop(Source As Control, X As Single, Y As Single)
Picture3.Picture = Source
End Sub

To open any file - Command Dialog Box
cdb1.ShowOpen
Open cdb1.filename For Input As #1

Printer Properties
Colormode, copies, devicename, drivername, duplex, height, orientation, page, paperbin, port, printquality, width, zoom

Printing to the printer object
Printer.Print "Yearly Report"


User Defined Function - UpperCase
Public Function uppercase(str As String) As String
Dim LN As Integer
Dim i As Integer

LN = Len(str)
For i = 1 To LN
If Asc(Mid(str, i, 1)) >= 97 And Asc(Mid(str, i, 1)) <= 122 Then
a = Asc(Mid(str, i, 1))
a = Chr(a - 32)
b = b & a
End If
Next i
uppercase = b

End Function

Private Sub Command1_Click()
Text1.Text = uppercase(Text1.Text)
End Sub

User defined Active X Controls
1. Start New Project : Active X Control (in place of standard Exe)
2. Toolboxbitmap property = Any bmp file
3. Go to project Properties = give project name and project description
4. Name property = NewControl
5. Save project = netcontrol.ctl

Subclassing the control
Add ins menu - add in manager - Active x control interface wizard -
dblclick - "Loaded" - ok
Place control on form - set name property - txtParent
Add ins - active x control interface wizard
Add items from left list to right list - select items and then >
- Next (Create custom members)
- New (to create your own properties, methods and events) - next
- Select all the items from left list except the new things which you have created. (shift + end …. Ctrl + click to unselect)
- Select maps to control dropdown and select txtParent
- Click next - set attribute window - only newly created things will appear in the "Public name" window.
- Look for default value and description for first property i.e. autosize
- Similarly for all other properties either set default value and description.
- Next - finish - close

Type following code after general declarations - declaration of public values for general access.
Public Enum AutoTSizeEnum
NA = 1
Small = 2
Medium = 3
Large = 4
End Enum
Public Enum ULTextEnum
AsIs = 0
Uppercase = 1
Lowercase = 2
End Enum

Left outs
About Dialog
User defined Property
Windows Common Controls
Status bar, Cool Bar, Image List, Toolbar, Month View, Date time picker, Graph
Web Browser
New Project - VB Application Wizzard - SDI - Next 4 menus - Finish
Connecting Help
Project Properties - Help file name
Creating Help File


Dim StrTitle As String
Dim StrTitleEntered As String

Private Sub Command1_Click()
StrTitleEntered = InputBox("Enter Bottom Title")
frmtitle.BottomTitle = "A new Property"

End Sub

Public Property Get BottomTitle() As Variant
BottomTitle = StrTitleEntered
End Property

Public Property Let BottomTitle(ByVal vNewValue As Variant)
StrTitle = StrTitleEntered
frmtitle.CurrentY = (frmtitle.Height - 600)
If frmtitle.CurrentY < 600 Then
Exit Property
Else
Print frmtitle.BottomTitle
End If
End Property

Private Sub Command2_Click()
MsgBox frmtitle.BottomTitle
End Sub

Private Sub Command3_Click()
Call TrialProc
End Sub




Calculator Codel

connection Code