Tuesday, March 10, 2020

Chapter 3 Introduction to SQL










Introduction
SQL is pronounced as Sequel and is an abbreviation for structured Query Language.  It was defined by Donald Chamberlin and others at the IBM Laboratory in 1974.

SQL does not use variables and control of flow statements hence it is often used as a database Sub-Language that can be added to a program written in a Host Programming Language which is called as Embedded SQL.  Following is the list of relational databases that supports SQL:-

Ø  SQL Server
Ø  Oracle
Ø  Access
Ø  Ingress
Ø  Sybase
Ø  Informix

SQL is used to query the database and gets results of the Query from the database.  The four major SQL statements are:- SELECT, INSERT, UPDATE AND DELETE.

Retrieving data
Select statement is the most common statement and is used to retrieve rows of data from a table.  When select statement is executed, database searches specified table extracts chose columns and select rows that meet a condition.  To select all the fields of a table an
astrick(*) should be used.  For example:

à        Select * from TitleAuthor
                          Book_No                   Author_ID
                          0-001417-7-5             A001
                          0-001413-8-8             A002
                          0-011129-1-6             A004
                        (TitleAuthor Table)

To select only Author_ID from TitleAuthor table:-
à        select Author_ID from TitleAuthor
                                    Author_ID
                                    A001
                                    A002
                                    A003
                                    A004
                        (TitleAuthor Table)

To omit duplicate columns DISTINCT clause can be used:-
à        select DISTINCT Author_ID from TitleAuthor
To sort records of the table Order by Clause can be used with select statement:-
à        Select * from Author
            Order by Author_Name
           
Author_ID               Author_Name               Phone_No
A003                         Sam Adams                    (206)555-6874
A004                         Ved Prakash                   NULL
A002                         Anthoney Desouza         (61)345-1247
A005                         Ritchi Waugh                 (265)234-1233
                        (Author Table)

Tables can be sorted with Ascending or Descending options as follows:-
à        Select * from Publisher
            Order by Pub_ID Desc
Pub_ID     Pub_Name           City
908             Barem Books        London
456             AGD Pub             Berlin
326             Peter Pub              Portland
  41             Prentice Hall         Calcutta
(Publisher Table)

To find out Author_Name ‘Ved Prakash’:-
à        Select Author_ID from Author
            Where Author_Name =’Ved Prakash’
                        Author_ID
                        A004

The Order by clause becomes relevant if we are looking more than one Author.
à        Select Author_ID, Author_Name
            From Author where Author_Name=
            “Sam Adams” or Author_Name =  “Ved Prakash”
            Order by Author_Name
                        Author_Id                  Author_Name
                        A002                           Sam Adams
                        A004                           Ved Prakash

With IN operator the query can be written to enable the value of an expression is equal to any of the several values in a list values should be separated by comma.
à        Select Author_ID, Author_Name
            from Author where Author_Name IN
            (“Sam Adams”, “Ved Prakash”)
            order by Author_Name

Besides IN keyword following keywords can be used with where clause:-
Ø  IN                                à        Checks value in a Range.
Ø  NOT IN                      à        Checks for values not in a Range.
Ø  LIKE                           à        Checks values that like a specified value.
Ø  NOT LIKE                 à        Checks values that not like a specified value.
Ø  IS NULL                    à        Checks for a NULL value.
Ø  IS NOT NULL           à        Checks for values that are not NULL.
Ø  AND                           à        Checks for multiple conditions.
Ø  OR                              à        Checks fro either of he two conditions.
Ø  BETWEEN                 à        Checks values between a set of values.
Ø  NOT BETWEEN        à        Checks for values not between a set of value.

Data can be retrieved with like operator.  Wild card characters used with like keyword are:-
-           For only one character.
[ ]         Any single character within a specified Range.
[^]        Any single character Not within specified Range.
%         Any Value.

à        Select * From Author
            Where Author_Name LIKE “S_ _ _”

Author_ID                 Author_Name                        Phone_No
A002                           Sam Adams                             (206)555-6874

à        Select * from Title
            Where Title Like “V%”

            Title                            Year    Pub_ID                                   Book_No
            Visual Basic 6.0          1998    326                              0-0014370

à        Select * from Title
            Where Title like “[^V]%”

à        Select Author_ID, Author_Name
            From Author Where Phone_No is NULL

à        Select * from Title
            Where Year between 1980 and 1999

Inserting data
Without any data we can not retrieve, update, and delete data.  Data can be inserted into a table with INSERT statement.

Syntax:
INSERT into (Table Name)
Values (Value1, Value2, Value3, ValueN . . . .)
à        Insert into Author
            values (“A006”, “Arti Prabhu”, “(022)-543-8818”)

Deleting data
With DELETE statement we can delete rows from a table.  DELETE has to be used with care as once the statement is executed there is no confirmation and rows get deleted.  After records are deleted we can not undo the operation.

Syntax:
DELETE from (Table Name)
[Where Condition]

à        Delete * from Title
Above command will delete all the rows from the database table.

à        Delete from Title
            Where Pub_Id = 41
Above command will delete a row where Pub_Id is 41.

Updating data
With UPDATE statement data can be updated or modified.

Syntax:
Update (Table Name)
Set Value_list [Where Condition]

à        Update Publisher
            Set City = “Bombay”
Above command will update all the rows in column City to Bombay.  Hence to prevent this where clause is used.

à        Update Publisher
            Set City = “Bombay”
            Where Pub_Name = “AGD Pub”

Referential Integrity
It is a rule on relational databases, used to ensure that relationships between records in related tables are valid.  Referential integrity is enforced when all of the following conditions are met:-

  1. We can not enter a value in Foreign Key field of related table that does not exist in primary key of Master table.
  2. A record can not be deleted from Master table if matching records exist in related table.
  3. We can not change a Primary Key value in Master table, if that record has related records.
Cursors
Cursors enables an application to use rows in the result set in a manner similar to using records in a sequential file.  With the help of cursors we can provide a mechanism to applications by mapping one row or a small block of rows from the result set into program variables.

We can define a cursor as a result set where browsing is enabled and current position of a record is known.

Types of cursors
The cursors are of four types and they are as follows:

1)                  Dynamic Cursors
Dynamic cursors detect all additions, changes and deletions made to rows in the result set, regardless of whether changes occur from inside the cursor or by other users outside the cursor.
It can be used in multi-user environment where each user needs to immediately view the changes made to a database by other users.  Dynamic cursors require more memory and network traffic when compared to keyset cursors.  Dynamic cursors provide forward and backward scrolling.

2)                  KeySet Cursors
Keyset cursors are controlled by a set of unique identifiers (keys) known as keyset.  Keys are a set of columns of result set that uniquely identify the rows in result set.
Keyset cursors behave like dynamic cursors but we can not view records that other users add, and prevents access to records that other users delete.  But we can still view the changes made to the data by other users.
It is used in multi-user environment when changes made to database by users have little or no effect on each other.  It allows forward and backward scrolling through the result set.

3)                  Static Cursors
It always displays result as it was when cursor was first opened.  They provide forward and backward scrolling. 
It do not detect updates, deletes and inserts made by other users.  These cursors are of limited use in data entry programs.

4)                  Forward-Only Cursors
It is default cursor type.  It enables to only forward through the result set.  It does not support a forward or backward scrolling in result set, it only supports fetching the rows serially from start to end of the result set. 
If an application does not require scrolling through the result, the forward only cursor is the best way for retrieving data quickly.


Top


Practical Session 3

Example 1 (Creating Program With ActiveX Objects)

Open project MDICourse_prj.  Add a new form to the above project.  Also add Sub Menu Option Find Course to Mdi Menu.  Design the Connection_frm interface as follows:-

Object
Property
Setting



Form
Name
Connection_frm

Caption
Course Details

MDI Child
True
Label1
Caption
Course Id
Label2
Caption
Course Title
Label3
Caption
Hours
Text1
Name
txtId
Text2
Name
txTitle
Text3
Name
txtHours
Text4
Name
txtFind
Command1
Name
cmdFirst

Caption
<< 
Command2
Name
cmdPrevious

Caption
< 
Command3
Name
cmdNext

Caption
> 
Command4
Name
cmdLast

Caption
>> 
Command5
Name
cmdAdd

Caption
&Add
Command6
Name
cmdCancel

Caption
&Cancel
Command7
Name
cmdDelete

Caption
&Delete
Command8
Name
cmdSave

Caption
&Save
Command9
Name
cmdExit

Caption
E&xit
Command10
Name
cmdFind

Caption
&Find
Frame1
Caption
Navigation Buttons
Frame2
Caption
 Action Buttons
Frame3
Caption
 Search Course ID

Save the Connection Form.  Save the project.  Select menu ProjectàReferencesàMicrosoft Data Binding Collection.  The form should look like as follows.

Add following lines of Code to Declaration Section
Dim Cnn1 As ADODB.Connection
Dim Rscourse As ADODB.Recordset
Dim addFlag As Boolean

To open a connection and Recordset to retrieve records, add following code to Load event of the form:-

Private Sub Form_Load( )
Set Cnn1 = New ADODB.Connection

Cnn1.Provider = "Microsoft.Jet.OLEDB.4.0"
Cnn1.Open "E:\Sandhya\MyCourse.mdb"

Set Rscourse = New ADODB.Recordset
Rscourse.Open "course", Cnn1, adOpenDynamic, adLockOptimistic, adCmdTable
addFlag = False
End Sub

Create private procedure Display and write the following Code:-
Private Sub Display( )
txtId.Text = Rscourse!CourseId
txtTitle.Text = Rscourse!CourseTitle
txtHours.Text = Val(Rscourse!Hours)
End Sub

Write the following code in to Form’s Activate Event
Private Sub Form_Activate( )
Display
End Sub
Private Sub Form_Unload(Cancel As Integer)
Cnn1.Close
End Sub

Search Course

Open the MDI Formà Open Click Event of mnuFindCourse and write following code lines:
Private Sub mnuCourseFind_Click( )
Connection_frm.show
End Sub

Write following individual Codes for other buttons also:-
Private Sub cmdAdd_Click( )
txtId.Text = ""
txtTitle.Text = ""
txtHours = ""
txtId.SetFocus
addFlag = True
cmdNext.Enabled = False
cmdFirst.Enabled = False
cmdPrevious.Enabled = False
cmdLast.Enabled = False
End Sub

Private Sub cmdCancel_Click( )
With Rscourse
.CancelUpdate
Display
cmdFirst.Enabled = True
cmdLast.Enabled = True
cmdNext.Enabled = True
cmdPrevious.Enabled = True
End With
End Sub

Private Sub cmdDelete_Click( )
Dim Res As Integer
Res = MsgBox("Wish to Delete Record", vbYesNo, "Confirm")
If Res = vbNo Then Exit Sub
With Rscourse
.Delete
.MovePrevious
If .EOF Then
.MoveLast
End If
If .BOF Then
.MoveFirst
End If
Display
End With
End Sub
Private Sub cmdExit_Click( )
Unload Me
End Sub

Private Sub cmdFind_Click( )
Dim Find_Str As String
Dim Cnn2 As ADODB.Connection
Dim rsSearch As ADODB.Recordset

If txtFind.Text = Empty Then
MsgBox "cannot be left empty"
txtFind.SetFocus
Exit Sub
End If

Find_Str = "select *from Course where CourseId ='" & txtFind.Text & "';"
Set Cnn2 = New ADODB.Connection
Cnn2.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source = E:\Sandhya\MyCourse.mdb"
Cnn2.Open
Set rsSearch = New ADODB.Recordset
rsSearch.Open Find_Str, Cnn2, adOpenDynamic, adLockOptimistic
If rsSearch.EOF And rsSearch.BOF Then
MsgBox "Invalid Course Id", vbOKOnly, "Stop!!"
Exit Sub
End If
txtId.Text = rsSearch!CourseId
txtTitle.Text = rsSearch!CourseTitle
txtHours.Text = rsSearch!Hours
Cnn2.Close
End Sub

Private Sub cmdFirst_Click( )
With Rscourse
.MoveFirst
Display
End With
End Sub
Private Sub cmdLast_Click( )
With Rscourse
.MoveLast
Display
End With
End Sub

Private Sub cmdNext_Click( )
With Rscourse
.MoveNext
If .EOF Then
.MoveLast
End If
Display
End With
End Sub

Private Sub cmdPrevious_Click( )
With Rscourse
.MovePrevious
If .BOF Then
.MoveFirst
End If
Display
End With
End Sub

Private Sub cmdSave_Click( )
With Rscourse
If adflag Then
.AddNew
Rscourse!CourseId = txtId.Text
Rscourse!CourseTitle = txtTitle.Text
Rscourse!Hours = Val(txtHours.Text)
Rscourse.Update
End If
End With
addFlag = False
End Sub

Private Sub txtFind_KeyPress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub

Private Sub txtHours_KeyPress(KeyAscii As Integer)
If Chr(KeyAscii) = vbBack Then Exit Sub
If Not IsNumeric(Chr(KeyAscii)) Then
KeyAscii = 0
MsgBox "Hours must Be Numeric", vbOKOnly, "Stop!!"
End If
End Sub



Top

Saturday, February 29, 2020

Chapter 2 Validating User Input








Designing a good interface
User interface is the link between user and application.  Usability of application depends on the interface.  Form is the basic element of user interface.

Properties
Are the characteristics of the controls on the form like size, color, screen location etc.  Properties for controls can be divided into categories.
Ø  Properties available only at design time.
Ø  Properties available only at run time.
Ø  Properties that can be set at any time.
To change a property in program code an assignment statement is used to set new value of the property.

Events
It is a user action directed at the application.  It is visual basic’s way of notifying that the form has received message from operating system.
When the code written in an event, is executed, event is said to be fired, or triggered.  Some events such as ‘key-down’ receive parameter from windows:-  For Example:

Private sub command1_KeyDown(KeyCode As Integer, Shift As Integer)
-------
End sub

Methods
A method is a code built into the interface components and can be executed at as required.

Form methods

Load
Initializes and loads the form in memory without displaying it on the screen.  If a form is not already loaded any reference to it automatically loads it into memory.

Syntax:
à        Load Form1

Unload
It removes a form from memory and frees system’s resources it is also useful to reset form properties to their original values.  Form can be unloaded by:-

Syntax:
à        Unload Form1             Or       
à        Unload Me

Hide
Hide removes form from the screen.  User can not access hidden forms controls.  Form can be hidden by:-

Syntax:
à        Form1.hide                  Or
à        Me.Hide

Show
Show loads a Form into memory if not loaded already and displays it on the screen.  A Form can be shown as:-

Syntax:
à        Form1.Show

Form events

Initialize
This event is triggered only once during the life time of an application, for which we have to exit and restart the application.  Form can be initialized by:-

Syntax:
à        Form1.Show               Or
à    Load Form1
à     
Load
Load event performs actions that are required before a form is displayed.  It is used to assign default values to the form and the controls on the form.  It occurs each time that a form is loaded into memory.  Load event can occur multiple times in lifetime of an application. 
For example:

Private Sub Form_Load( )
Text1.text = “Hello EveryBody”
End Sub

Activate/Deactivate
These events are triggered when user moves between two or more forms within same application.

Activate event is triggered when a form receives focus from another form in the same project.  It is fired before Got_Focus event.  Activate event occurs only if form is visible.

Deactivate event is fired after lost_focus event i.e. after a from loses a focus to another form.

Query-unload
It determines how a form was closed.  This event is occurs before unload event is occurred.  Unload mode argument indicates how the form was closed and can be used to cancel an event.

Argument                    Value    Description
vbFormControlMenu    0            Close command of control menu on form is chosen.
vbFromCode                 1            Unload statement is evoked from the code.
vbAppWindows           2            Current window operating system is ending.
vbAppTaskManger       3            Application is closed by window’s task manager
vnFormMDIForm         4            MDI child form closes because MDI parent form is
                                                    closed.
To display how form was unloaded write following code:-

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If UnloadMode =vbFormCode then
Msgbox “You invoked Unload Statement”
Cancel = False
End If
End Sub

Terminate
It is triggered when all instances of a form are removed from memory.  It occurs after unload event.  To free form’s variables from memory, set the from equal to Nothing.  For example:
Set Form1 = Nothing

Events for Control

Keydown
Occurs as user presses the key.  It determines whether Shift and Control keys were being held down as key was pressed.  Following displays Message for Home Key

Private Sub Text1_Keydown(KeyCode As Integer, Shift As Integer)
If KeyCode = VbKeyHome then
Msgbox “You pressed Home Key”
End If
End Sub

Keyup
Occurs as the user releases key.  Determines whether Shift and Control key were being held down as the key was pressed.  Following code displays number of times a key is pressed on toolbox.

Private Sub Text1_keyUp(KeyCode as Integer, Shift as Integer)
Static Kp as Integer
Kp = Kp+1
Label1.caption = kp
End Sub

KeyPress
Occurs between Keydown and KeyUp events.  Interprets ASCII value of key pressed.  Following code converts text into Uppercase letters.

Private Sub Text1_keyPress(Key ASCII As Integer)
txt=chr(keyASCII)
Keyascii = ASC(UCase(txt))
End Sub

MouseDown
Occurs when mouse button is pressed.

Private Sub Text1_mouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If button =1 then
MsgBox “You pressed Left Button”
Elseif button = 2 then
MsgBox “You pressed Right Button”
End If

MouseUp
Occurs when user Releases the mouse button.  Following is the code to empty the contents of second text box.

Private Sub Text1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Txt2.Text = Empty
End Sub

Click
Occurs when user clicks left mouse button.  Following code changes caption of the button.
Private Sub Command1_Click( )
Command1.Caption = “Hi”
End Sub

DblClick
Occurs when user presses and releases the mouse button twice.
Private Sub List1_DblClick( )
List1.RemoveItem List1.ListIndex
End Sub

Data validation
Data validation ensures that data entered in application is accurate and a valid data type.  It also verifies data type.  In visual basic there are two data validation techniques:-
Ø  Form Level Validation
Data is verified after user enters all fields on the form.

Ø  Field Level Validation
Data in the fields are verified one at a time after the user fills in the fields.

Form level validation
Controls support some methods and events that are useful for validation and validation of data.  Some of them are:-

Set focus method
It is the ability of a form or a mouse click.  In Microsoft Windows only one window, form or control can have focus at a time.  Set focus method allows to change focus between controls programmatically.  For example:-

If txtName.Text = “ “ then
Beep
MsgBox “Name should not be empty
txtName.SetFocus
End If

Lost focus method
When a form or a control loses a focus, LostFocus event is fired.  Focus is lost when a user tabs to another field or clicks on another field.  This event is used for validation.  For checking the data just as the user is leaving the field.  For example:

Private Sub TxtCode_LostFocus( )
If Len(TxtCode.Text)<> 4 then
Beep
MsgBox  “Code should be of 4 characters”
Txtcode.SetFocus
End If

Mask property
Can be set at design time or at run time.  It is used to validate code like correct month or time of the day or standard formats at design time.  Each characters position in the control corresponds to either a place holder or a literal character.  A literal character or a ‘literal’ can give visual cues about the type of data being used. 

For example parenthesis surrounding area code of a telephone number are literals:( 61).

Mask for date can be :- MaskEditBox1.Mask=”##/##/####”

Creating menus
Menus provide a structured way for users to access the commands and tools in an application.  First step in creating a menu would be to group logically related items together.

Guidelines for designing a Menu
  1. Menu items should be grouped together by their properties.
  2. Groups should be limited to five items or less.
  3. Function groups should be separated using separator bars.
  4. Visual Basic allows six levels of submenus to be created.  But if possible, number of submenu levels should be limited to two.  As too many levels make it confusing for the user to understand the application.

Creating Menu at Design Time
At design time the menu editor is only means to create or modify a menu.  Only name and caption properties need to be specified for a menu item.  Name property must be unique for each menu item.  The hyphen (-) creates separator bar to divide menu options into logical groups.  Separator bar do not respond to click event. 

A menu item can not be a separator bar if it is a menu title, has submenu items, is checked or disabled.  After completing a menu; codes should be written for the click event of menu items.

Menu item properties

Ø  Checked
Indicates whether a menu item is turned on or off; and which item was last used.
Ø  Enabled
Determines whether a menu item can be accessed.  If this property is set to false the item appears with gray color and user can not access any sub-level menus.
Ø  Visible
Determines whether user can see the menu.  If this property is set to false item and its sub-level menus are not shown in the menu.
Ø  WindowList
Maintains a list of open windows and displays a check mark next to active window.
Ø  Index
Enables to create additional items at run time.
Ø  helpContextId
identifies help topic that is accessed if F1 key is pressed which the menu item is selected.

Menu items and shortcut keys
Access key and short cut keys enables keyboard access to menu items.  Access key allows us to access a menu item by pressing Alt Key and designated letter.

Pop-up menu
A pop-up menu displayed at the cursor location when user clicks the right mouse button.  We can create a pop-up menu in two steps.-
1)         Create the menu using Menu Editor,
2)         Activate the menu using Pop-up method.

Following is the code added in Mouse_Down event of a form, which has a menu item “Edit” with the name property set to mnuEdit and with a submenu.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If button = vbRightButton then
PopupMenu mnuEdit
End if
End Sub

Toolbar and status bar
Toolbar consist of buttons, corresponds to items in an application’s menu.  Buttons can be added or removed from the toolbar using Add and Remove methods.  The key and Index properties are required to identify the buttons.
Status bar appears at the bottom of the form and displays status data in an application.  There can be 16 panels on the status bar, each of which can contain a text or a picture.  Important properties that control appearance of the panels on the status bar are Width, Alignment (Text or Picture), Style and Bevel used to display date, time and keyboard status.

Multiple document interface
Multiple document interfaces(MDI) allows to create applications that contain multiple forms within single container form, called as MDI parent form and the form contain within it are called as MDI child forms.  Each child form is displayed within its own window, which in turn is contained within parent MDI form.

A visual basic application can have only one MDI form, which is the parent form.  All other forms are the child forms.  A form can be made MDI child form by setting its MDIChild property to true.  MDI child forms can be maximized, minimized and moved inside the parent MDI form.


Top



Practical Session 2

Employee Details Form

Example 1 :    Invoke Visual Basic Design the Interface as under.  Place all other controls, to place status bar control click Projectà Components à and select Microsoft Windows Common Controls 6.0 (SP4).  The objects and their properties are as follows:-
Object                                      Property                                              Setting            
Form                                       Name                                                  Empfrm
                                                Caption                                               Employee Details

Label1                                    Name                                                  lblCode
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Employee Code:

Label2                                    Name                                                  lblName
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Employee Name:

Label3                                    Name                                                  lblDept
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Department:

Label4                                    Name                                                  lblGrade
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Grade:

Label5                                    Name                                                  lblBasic
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Basic Salary:

Label6                                    Name                                                  lblDesg
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Designation:

Label7                                    Name                                                  lblJoinDt
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Date of Joining:

Label8                                    Name                                                  lblList
                                                Alignment                                           1 – Right Justify
                                                Caption                                               Record List:

Label9                                    Name                                                  lblCount
                                                Alignment                                           1 – Right Justify
                                                Caption                                               No  of Employees:

Text1                                      Name                                                  txtCode
                                                MaxLength                                         4
                                                Text                                                     -

Text2                                      Name                                                  txtName

Text3                                      Name                                                  txtBasic
                                                Enabled                                               False
                                                Text                                                     -
Text4                                      Name                                                  txtDate
                                                Text                                                     -

Text5                                      Name                                                  txtDate
                                                Enabled                                               False
                                                Text                                                     -

Frame1                                   Caption                                               Sex
                                                Enabled                                               False

Option1                                  Name                                                  OptMale
                                                Caption                                               Male

Option2                                  Name                                                  OptFemale
                                                Caption                                               Female

Combo1                                  Name                                                  cboTitle
                                                Style                                                    2-Dropdown List

Combo2                                  Name                                                  cboDept
                                                Style                                                    2-Dropdown List

Combo3                                  Name                                                  cboGrade
                                                Style                                                    2-Dropdown List

Combo4                                  Name                                                  cboDesg
                                                Style                                                    2-Dropdown List

List1                                        Name                                                  lstDet
                                                Enabled                                               False

Command1                            Name                                                  cmdAdd
Caption                                               &Add
Enabled                                               False

Command2                            Name                                                  cmdRemove
                                                Caption                                               &Remove
Enabled                                               False                           

Command3                            Name                                                  cmdClsForm
Caption                                               Clear &Form
Enabled                                               False   

Command4                            Name                                                  cmdClsList
Caption                                               Clear &List
Enabled                                               False                           

Command5                            Name                                                  cmdExit
Caption                                               E&xit

Write the Following codes for individual Controls:-
Private Sub cboDept_GotFocus( )
StatusBar1.Panels(3).Text = "Select Department For The Employee"
If txtName.Text = Empty Then
StatusBar1.Panels(3).Text = "Enter Employee Name"
txtName.SetFocus
End If
End Sub

Private Sub cboDesg_GotFocus( )
StatusBar1.Panels(3).Text = "Select Designation For Employee "
If cboGrade.Text = "" Then
StatusBar1.Panels(3).Text = "Select Grade For Employee "
cboGrade.SetFocus
End If
End Sub

Private Sub cboGrade_Click( )
Select Case cboGrade.Text
Case "E1"
txtBasic.Text = 2100
cboDesg.Clear
cboDesg.AddItem "Trainee"
cboDesg.AddItem "Team Manager"

Case "E2"
txtBasic.Text = 3200
cboDesg.Clear
cboDesg.AddItem "Junior Executive"
cboDesg.AddItem "Senior Executive"

Case "E3"
txtBasic.Text = 4200
cboDesg.Clear
cboDesg.AddItem "Team Leader"
cboDesg.AddItem "Project Manager"

Case "E4"
txtBasic.Text = 6000
cboDesg.Clear
cboDesg.AddItem "Division Head"
cboDesg.AddItem "Group Head"
End Select
End Sub
Private Sub cboGrade_GotFocus( )
StatusBar1.Panels(3).Text = "Select a Grade For The Employee"
If cboDept.Text = Empty Then
StatusBar1.Panels(3).Text = "Select a Designation For The Employee"
cboDept.SetFocus
End If
End Sub

Private Sub cboTitle_Click( )
If cboTitle.Text = "Mrs." Or cboTitle.Text = "Ms." Then
optFemale.Value = True
Frame1.Enabled = False
ElseIf cboTitle.Text = "Mr." Then
optMale.Value = True
Frame1.Enabled = False
End If
End Sub

Private Sub cboTitle_GotFocus( )
StatusBar1.Panels(3).Text = "Select a Title For The Employee"
If txtCode.Text <> Empty Then
If txtCode.Text Like "[A-Z]###" <> True Then
StatusBar1.Panels(3).Text = "Code Should Begin With A Character Followed by 3 Digits"
txtCode.SetFocus
Exit Sub
End If
StatusBar1.Panels(3).Text = "Enter Employee Code"
txtCode.SetFocus
End If
cmdClsForm.Enabled = True
End Sub

Private Sub cmdAdd_Click( )
Dim mystring As String, res_str As String
For i = 0 To lstDet.ListCount - 1
my_string = lstDet.List(i)
res_str = Left(mystring, 4)
If txtCode.Text = res_str Then
StatusBar1.Panels(3).Text = "Employee Code Already Exists"
MsgBox "Employee Code Already Exists"
txtCode.SetFocus
Exit Sub
End If
Next i
If txtCode.Text Like "[A-Z]###" = True Then
lstDet.AddItem txtCode.Text + " " + cboTitle.Text + " " + txtName.Text + " " + txtDate.Text
txtCount.Text = lstDet.ListCount
cmdRemove.Enabled = True
cmdClsList.Enabled = True
Form_Load
txtCode.SetFocus
Else
txtCode.SetFocus
End If
End Sub

Private Sub cmdAdd_GotFocus( )
If txtDate.Text = "" Then
StatusBar1.Panels(3).Text = "Enter Date"
txtDate.SetFocus
ElseIf txtName.Text = "" Then
StatusBar1.Panels(3).Text = "Enter Employee Name"
txtName.SetFocus
End If
End Sub

Private Sub cmdClsForm_Click( )
Form_Load
txtCode.SetFocus
cmdAdd.Enabled = False
End Sub

Private Sub cmdClsList_Click( )
lstDet.Clear
txtCount.Text = 0
cmdRemove.Enabled = False
cmdClsList.Enabled = False
cmdAdd.Enabled = False
txtCode.SetFocus
End Sub

Private Sub cmdExit_Click( )
Unload Me
End Sub
Private Sub cmdRemove_Click( )
StatusBar1.Panels(3).Text = "Select Employee Record To be Removed From Record List"
lstDet.Enabled = True
If lstDet.ListIndex > -1 Then
lstDet.RemoveItem lstDet.ListIndex
txtCount.Text = lstDet.ListCount
txtCode.SetFocus
lstDet.Enabled = False
End If
If lstDet.ListCount = 0 Then
cmdRemove.Enabled = False
cmdClsList.Enabled = False
txtCode.SetFocus
lstDet.Enabled = False
End If
End Sub

Private Sub Form_Load( )
Dim mypanel As Panel
StatusBar1.Panels.Clear
Set mypanel = StatusBar1.Panels.Add(1, , , sbrDate)
mypanel.AutoSize = sbrNoAutoSize
mypanel.Bevel = sbrInset
setmypanel = StatusBar1.Panels.Add(2, , , sbrTime)
mypanel.AutoSize = sbrNoAutoSize
mypanel.Bevel = sbrInset
mypanel.Alignment = sbrLeft
Set mypanel = StatusBar1.Panels.Add(3)
StatusBar1.Panels(3).Text = "Status"
StatusBar1.Panels(3).AutoSize = sbrSpring

txtCode.Text = ""
txtName.Text = ""
txtBasic.Text = ""
txtDate.Text = ""

optMale.Value = False
optFemale.Value = False
cmdAdd.Enabled = False

cboTitle.Clear
cboDept.Clear
cboGrade.Clear
cboDesg.Clear

cboTitle.AddItem "Mr."
cboTitle.AddItem "Mrs."
cboTitle.AddItem "Ms."

cboDept.AddItem "Accounts"
cboDept.AddItem "EDP"
cboDept.AddItem "HRD"
cboDept.AddItem "Sales"

cboGrade.AddItem "E1"
cboGrade.AddItem "E2"
cboGrade.AddItem "E3"
cboGrade.AddItem "E4"
End Sub

Private Sub txtCode_GotFocus( )
StatusBar1.Panels(3).Text = "Code Should Begin With A Character Followed by 3 Digits"
End Sub

Private Sub txtCode_KeyPress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub

Private Sub txtDate_GotFocus( )
StatusBar1.Panels(3).Text = "Enter Date in dd/mm/yyyy format"
cmdAdd.Enabled = True
If cboDesg.Text = "" Then
StatusBar1.Panels(3).Text = "Select Designation for the Employee"
cmdAdd.Enabled = False
cboDesg.SetFocus
End If
End Sub

Private Sub txtDate_LostFocus( )
Dim dt
dt = txtDate.Text
If Not validdate(dt) Then
StatusBar1.Panels(3).Text = "Valid Date must be Given as in dd/mm/yyyy format"
txtDate.Text = ""
Exit Sub
Else
txtDate.Text = Format(dt, "dd/mm/yyyy")
End If
End Sub

Private Sub txtName_GotFocus( )
StatusBar1.Panels(3).Text = "Enter Employee Name"
If Len(cboTitle.Text) = 0 Then
StatusBar1.Panels(3).Text = "Select a Title for The Employee Name"
cboTitle.SetFocus
End If
End Sub

Private Sub txtName_KeyPress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
If KeyAscii = 32 Then Exit Sub
If IsNumeric(Chr(KeyAscii)) Or _
(KeyAscii >= 33 And KeyAscii <= 64) Or _
(KeyAscii >= 91 And KeyAscii <= 96) Or _
(KeyAscii >= 123 And KeyAscii <= 126) Then
KeyAscii = 0
StatusBar1.Panels(3).Text = "Employee Name Should Be Characters"
End If
End Sub

Public Function validdate(dt) As Boolean
Dim hold As Variant
hold = dt
validdate = IsDate(hold)

End Function 


Example 2 (Creating Database Application With VB’s Inbuilt DataBase)
Design the Interface As follows:
Place Three Labels and Three Text Boxes. 

Ado Data ControlAlso add Data Control on the form.  Select Connection as “Access” and Data Source for Data Control as “Biblio.mdb”.  Select the Record Source (Table) “Authors” for Data Control.  

Design the Inter Face as Under:-
AdoData Form



Bind the Text Controls with Data1 and set their individual fields with the fields of the table in properties window.

Example 3(Creating Simple Menu)

Menu Editor Select ToolsàMenu  Editor. Or Right click on the Form and Select Menu Editor.
1) Specify Caption for the Menu Option and the Name for it.
2) Click on à button to insert submenu options.
3) Enter other menus as per program requirement.
                                                            
Menu
Write the Code For menu Controls As follows:
Private Sub mnuExit_Click( )
Unload Me
End Sub
Private Sub mnuNew_Click( )
MsgBox "Well You Clicked For New Item"
End Sub

Private Sub mnuOpen_Click( )
MsgBox "What do you want to open??"
End Sub

Example 3 (MDI Application)
1)                  Create new project
2)                  Add a MDI Form
3)                  Set Caption to Leena’s Software Education
4)                  Set Window State Property  to 2-Maximized
5)                  Attach Following menu to MDI Form1

Menu Option
(Caption)
Menu Option
(Name)
Submenu Option
(Caption)
Submenu Option
(Name)
&File
mnuFile
&Add
mnuAdd


-
mnuSep1


E&xit
mnuExit
&Window
mnuWindow
Tile &Horizontally
mnuHorz


Tile &Vertically
mnuVert


&Cascade
mnuCascade
Add submenu option for Add as following:

Submenu Option (Caption)              Menu Option (Name)
                                   &Course Details                                 mnuCourse

Save the MDIForm as Mdi_form.  Save project as MDICourse_prj.  Save form1 as Course_frm.  Open Course_frm form and design the interface as follows:-

Object
Property
setting
Form
Name
Course_frm

Caption
Course Enquiry

MDI Child
True
Label1
Caption
Course Id
Label2
Caption
Course Title
Label3
Caption
Hours
Text1
Name
txtId
Text2
Name
txTitle
Text3
Name
txtHours
Command1
Name
cmdAdd

Caption
&Add
Command2
Name
cmdDelete

Caption
&Delete
Command1
Name
cmdExit

Caption
E&xit

 
To design the following interface first create a database MyCourse in Microsoft Access, and then create Course table with CourseId, CourseTitle and Hours Fields.

Course Inquiry FormSelect Project àSelect Components.
Select Microsoft ADO Data Control 6.0 (OLE DB).  Click OK.

Place ADO Data Control on the form.  Select ADO Data Control ‘Adodc1’

Set Name to adCourse.  Set Caption property to Course.  Save the form.

Now select ADO Data Control. Right Click on it and select Properties.  Click Build Button. Select Jet 4.0 OLEDB Provider. Click Next>> button.  Click on the ellipses near to select or enter data base name.  

Select MyCourse database in Access and click on Open button.  Click on the Test Connection Button.  If database name and provider etc information is correct then a message box confirming Test Connection succeeded will appear then click Ok twice.  

Select Record Source Property.  In the Command Type Object select the item 2-adCmdTable.  Select the Table Course from the Table or Stored Procedure Name.  Click OK Button.  Save the form.  Now bind the text controls with Data Source as above and Data Field to their individual Fields.  And write the following codes.

Private Sub cmdAdd_Click( )
adCourse.Recordset.AddNew
txtId.SetFocus
End Sub

Private Sub cmdDelete_Click( )
adCourse.Recordset.Delete
adCourse.Recordset.MoveNext
If adCourse.Recordset.EOF = True Then
adCourse.Recordset.MovePrevious
End If
End Sub
Private Sub cmdExit_Click( )
Unload Me
End Sub

Private Sub Form_Load( )
course.Height = 7000
course.Width = 10000
End Sub

Private Sub txtHours_KeyPress(KeyAscii As Integer)
If Chr(KeyAscii) = vbBack Then Exit Sub
If Not IsNumeric(Chr(KeyAscii)) Then
KeyAscii = 0
MsgBox "Hours must Be Numeric", vbOKOnly, "Stop!!"
End If
End Sub

Private Sub txtId_KeyPress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub

Private Sub txtTitle_KeyPress(KeyAscii As Integer)
If KeyAscii = 32 Then Exit Sub
If IsNumeric(Chr(KeyAscii)) Or _
(KeyAscii >= 33 And KeyAscii <= 64) Or _
(KeyAscii >= 91 And KeyAscii <= 96) Or _
(KeyAscii >= 123 And KeyAscii <= 126) Then
KeyAscii = 0
End If

End Sub







Top