UG BCA Computer Applications 101 64 Lab Visual Basic Programming BCA 4357
UG BCA Computer Applications 101 64 Lab Visual Basic Programming BCA 4357
B.C.A.
VI - Semester
101 64
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No.AU/DDE/DE12-27/Preparation and Printing of Course Materials/2020 Dated 12.08.2020 Copies - 500
LAB: VISUAL BASIC PROGRAMMING
Self-Instructional
Material
Lab: Visual Basic
BLOCK 1 Programming
Self-Instructional
2 Material
Now, add some code to pause the application and requesting for the user input. Lab: Visual Basic
Programming
Console.Write(“Press any key to continue...”)
Console.ReadKey(true)
Note: Select Build Build Solution on the menu bar. NOTES
It will compile the program in intermediate language (IL) that is converted by Just-
In-Time (JIT) compiler into binary code.
Step 4: Save and Test
Run the program in Debug mode.
Self-Instructional
Material 3
Lab: Visual Basic Table 1.1 Intrinsic Controls and their Description
Programming
S. Control Prefix Description
NO.
1 Label Ibl Displays text on a form
2 Frame fra Serves as a container for other controls
NOTES 3 CheckBox chk Enables users to select or deselect an option
4 ComboBox Cbo Allows users to select from a list of items or add a new value
5 HscrollBar hsb Allows users to scroll horizontally through a list of data in another
control
6 Timer tmr Lets your program perform actions in real time, without user interaction
7 DirListBox dir Enables users to select a directory or folder
8 Shape shp Displays a shape on a form
9 Image img Displays graphics (images) on a form but can't be a container
10 OLE Container ole Enables you to add the functionality of another Control program to your
program
11 PictureBox pic Displays graphics (images) on a form and can serve as a container
12 TextBox txt Can be used to display text but also enables users to enter or edit new or
existing text
13 CommandButton cmd Enables users to initiate actions
14 OptionButton opt Lets users select one choice from a group; must be used in groups of two
or more
15 ListBox lst Enables users to select from a list of items
16 VscrollBar vsb Enables users to scroll vertically through a list of data in another control
17 DriveListBox drv Lets users select a disk drive
18 FileListBox fil Lets users select a file
19 Line lin Displays a line on a form
20 Data dat Lets your program connect to a database
Control Arrays
A control array is a group of controls having the same name type and event
procedures. Control arrays uses fewer resources in comparison to adding multiple
control of same type at design time. They can be created at design time only. You
can create the control array using the any of the three methods given below.
1. You can create a control array with only one element using a control and
assigning that a numeric, non-negative value to its Index property.
2. You create two controls of the same class with an identical Name property.
VB display a dialog box warning that there is already a control having same
name and asks to create another control array. Click on the Yes button.
3. Select a control on the form and copy it to the clipboard, and paste a new
instance of the control having the same Name property as the original one.
Visual Basic shows the warning as in method second.
Control arrays are one of the most interesting features of the VB that adds
flexibility to your programs. All controls in a control array have the same set of
event procedures that result in reduced amount of code you have to write to
respond to a user’s actions. Consider an example, if you have a control array of
10 textboxes call txtField, indexed 0 to 9, and then you can use one GotFocus
event among all the 10 members instead of using 10 different GotFocus events.
VB will automatically pass an Index parameter to the event procedure to
differentiate which member of the control array is being acted upon. The code of
GotFocus event procedure for the txtField control array might look as given below:
Private Sub txtField_GotFocus(Index As Integer)
Self-Instructional txtField(Index).SelStart = 0
4 Material
txtField(Index).SelLength = Len(txtField(Index).Text) Lab: Visual Basic
Programming
End Sub
Or
Private Sub txtField_GotFocus(Index As Integer)
NOTES
With txtField(Index)
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
In Visual Basic 6, the importance of using control arrays as a means of
dynamically creating new controls at run time is reduced. It has introduced a new
and more powerful capability.
Syntax for refering to a member of a control array is:
ControlName(Index)[.Property]
For events where VB already passes a parameter (for example, the
textbox’s KeyPress event where VB passes the KeyAscii parameter),
VB will add “Index” as the first parameter, followed by the parameters
that are usually passed to the event. The syntax for procedure header of
the KeyPress event of the txtField control array will be:
Private Sub txtField_KeyPress(Index As Integer, KeyAscii
As Integer)
Program 1.1: Create a form to enter total sales for five years in textboxes. All the
sales values of 5 years are added and displayed in the label under the button on
clicking Calculate button.
The labels and textboxes for reading sales values are created as Control
Arrays of labels and textboxes respectively.
Design of Data Entry Form
Calculate Button(btnCalculate) and Label (lblTotal) for displaying the total sales
of 5 years is in the design of the form.
Self-Instructional
Material 5
Lab: Visual Basic Data Entry Form at Runtime
Programming
Control arrays for Labels and Textboxes are declared when the form is executed.
These control arrays elements are added and displayed on the form in the form_load
NOTES event. When a user fills the values in textboxes and clicks the Calculate Button
then a for loop is used to get values from textbox control array and add them
together in a variable total. After completing loop label lblTotal’s text property is
set with variable total’s value.
Public Class Form1
Dim lblValues(4) As Label ‘control array of labels
Dim txtValues(4) As TextBox ‘control array of textboxes
Dim intCount As Integer
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
For intCount = 0 To 4
‘ Delcare text box and label variable that are added as elements of control
arrays
Dim MyTextbox As New TextBox
Dim MyLabel As New Label
‘Set left and top values of labels to define display position in the form
MyLabel.Left = 10
MyLabel.Top = 10 + 25 * intCount
‘set the text of labels
MyLabel.Text = “Year “ + CStr(intCount + 1)
‘set width of the labels
MyLabel.Width = 50
‘add newly created label as an element at the current index defined by
intCount of the label control array
lblValues(intCount) = MyLabel
‘add the label control array element on the form using controls collection
Me.Controls.Add(lblValues(intCount))
‘Set left and top values of textboxes to define display position in the form
MyTextbox.Left = 100
MyTextbox.Top = 10 + 25 * intCount
‘add newly created textbox as an element at the current index defined by
intCount of the textbox control array
txtValues(intCount) = MyTextbox
‘add the textbox control array element on the form using controls collection
Me.Controls.Add(txtValues(intCount))
Next
Self-Instructional
6 Material End Sub
Private Sub btnCalculate_Click(ByVal sender As Lab: Visual Basic
System.Object, ByVal e As System.EventArgs) Handles Programming
btnCalculate.Click
Dim total as Double ‘ variable to store sum of sales while iterating through
control array of textboxes NOTES
For intCount = 0 To 4
‘Add values from textboxes to variable total using += assignment operator
total += Val(txtValues(intCount).Text)
Next
‘change fore color of display label
lblTotal.ForeColor = Color.Red
‘display total in label at form bottom
lblTotal.Text = “Total 5 years sales is “ + CStr(total)
End Sub
End Class
Output:
BLOCK 2
Step 2: Right click on Mdi_From in solution explorer and add two forms by
clicking over ADD option therein and Name them Form2 and Form3 respectively.
Customize these Form2(Child1_form) and Form3(Child2_form) as shown below
to make them to perform as two separate functions.
Step 3: Customise each control pasted on the Form2 and Form3 as per the
functions specified on labeled as show above. After customizing these form2. vb
Self-Instructional and Form3.vb, the code behind them will be as shown below:
8 Material
Form2.vb Lab: Visual Basic
Programming
‘From2.vb
‘Program to demonestrate the use of MDI Form to perform
Addition operation
NOTES
Public Class Child1_form
Private Sub Label1_Click(sender As Object, e As EventArgs)
Handles Label1.Click
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
Dim sum As Integer
sum = Convert.ToInt32(TextBox1.Text) + Convert.
ToInt32(TextBox2.Text)
TextBox3.Text = sum
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs)
Handles Button2.Click
TextBox1.Text = “ “
TextBox2.Text = “ “
TextBox3.Text = “ “
End Sub
End Class
Form3.vb
‘From3.vb
‘Program to demonestrate the use of MDI Form to perfrom
Subtration Operation
Public Class Child_form2
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
Dim subt As Integer subt = Convert.ToInt32(TextBox2.Text)
- Convert. ToInt32(TextBox1.Text) TextBox3.Text = subt
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs)
Handles Button2.Click
TextBox1.Text = “ “
TextBox2.Text = “ “
TextBox3.Text = “ “
End Sub
End Class
Self-Instructional
Material 9
Lab: Visual Basic Application with Dialogs
Programming
Dialog boxes are used for user interaction and information retrieval. In simple
terms, a dialog box is a shape that is set to FixedDialog with its FormBorderStyle
NOTES enumeration property. You can make your own custom dialog boxes using Visual
Studio’s Windows Forms Designer.Add controls such as Textbox, Label, and
Button to customize dialog boxes as per your needs. The .NET Framework includes
predefined dialog boxes, such as File Open and message boxes that can be altered
for your own applications.
Dialog Box Creation
You have to start with a Form to create a dialog box, which can be obtained by
creating a Windows application.
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Text = “Domain Configuration”
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = FormStartPosition.CenterScreen
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
Self-Instructional
10 Material
Output: Lab: Visual Basic
Programming
NOTES
Now, click on the Click Me button of the Windows Form, it displays the
dialog box, as shown below.
Self-Instructional
Material 13
Lab: Visual Basic Applications with Menus
Programming
In VB6, the MainMenu feature was not present; it was added to VB.NET. But,
as in previous versions of VB, you can use the methods and properties of the
NOTES Menu portion to add and change menu items in either design-time or run-time.
Working with Menus in Design-Time
You need to add a MainMenu attribute to your form to add menus to your VB.NET
application during design-time. You can build, add, and change menus and menu
bars with the MainMenu control and set their properties in the Properties window.
To add a MainMenu component, open the Forms Toolbox and add the MainMenu
component to your form.Once you have added the control to your form, you
quickly can add menus to your VB.NET windows forms.
In Windows type, a menu is used as a menu bar containing a list of related
commands and is executed via MenuStrip Control also known as the VB.NET
MenuStrip Control. The Menu control. Menu items are created with
ToolStripMenuItem Objects. In addition, the ToolStripDropDownMenu and
ToolStripMenuItem objects allow complete structure control, appearance,
functionalities to create menu items, submenus, and drop-down menus in a
VB.NET application.
Step 1: Drag the MenuStrip control from the toolbox and drop it on to the Form.
Self-Instructional
14 Material
Step 2: We can set various properties of the Menu by clicking on the MenuStrip Lab: Visual Basic
Programming
control once the MenuStrip is added to the form.
NOTES
Properties Description
CanOverflow It gets or sets a value indicate that the MenuStrip supports overflow
functionality.
GripStyle It gets or sets the visibility of the grip used to reposition the control.
MdiWindowListItem It gets or sets the ToolStripMenuItem that is used to display a list of
Multiple-document interface (MDI) child forms.
Stretch It gets or sets a value indicating whether the MenuStrip stretches
from end to end in its container.
ShowItemToolTips It gets or sets a value indicating whether ToolTips are shown for the
MenuStrip.
Events Description
MenuActivate Happen when the user accesses the menu with the
keyboard or mouse.
MenuDeactivate Happen when the MenuStrip is deactivated.
Windows Forms contain a rich set of classes for creating your own custom
menus with modern appearance, look and feel. The MenuStrip,
ToolStripMenuItem, ContextMenuStrip controls are used to create menu bars
and context menus efficiently.
Controls Description
MenuStrip It provides a menu system for a form.
ContextMenuStrip It represents a shortcut menu.
ToolStripMenuItem It represents a selectable option displayed on a MenuStrip or
ContextMenuStrip. The ToolStripMenuItem control replaces and
adds functionality to the MenuItem control of previous versions.
Self-Instructional
Material 15
Lab: Visual Basic Methods of the MenuStrip Control
Programming
Methods Description
CreateAccessibilityInstance() It is used to create a new accessibility instance for the
MenuStrip Control.
NOTES CreateDefaultItem() The CreateDefaultItem method is used to create a
ToolStripMenuItem with the specified text, image, and event
handlers for the new MenuStrip.
ProcessCmdKey() The ProcessCmdKey method is used to process the command
key in the MenuStrip Control.
OnMenuActivate() It is used to initiate the MenuActivate event in the MenuStrip
control.
OnMenuDeactivate() It is used to start the MenuDeactivate event in the MenuStrip
control.
In the screenshot below, we have created the menu and sub-items of the
menu bar in the form.
Now, we write the Shortcut keys for the File subitems, such as NewCtrl
+ N, Open Ctrl + O, etc.
Self-Instructional
16 Material
After that, we can see the subitems of the Files with their Shortcut keys, Lab: Visual Basic
Programming
NOTES
Self-Instructional
Material 17
Lab: Visual Basic Click on the File menu that shows the multiple options related to files.
Programming
NOTES
Self-Instructional
18 Material
Properties of Data Controls Lab: Visual Basic
Programming
3. Give it a name of Students and click OK. After that you will now see Students
in the list of databases.
Self-Instructional
Material 19
Lab: Visual Basic 4. Expand Students in the database list, and right click on Tables, then select
Programming
New Table.
NOTES
Self-Instructional
20 Material
2. Select Blank Database. Lab: Visual Basic
Programming
NOTES
3. On the right side of the screen enter the File name, Students.accdb (in this
case) and click Create.
4. Inside the new Screen, edit the Columns and data to reflect.
NOTES
Self-Instructional
22 Material
Consider an example of loading an image file in a picture box, using the open file Lab: Visual Basic
Programming
dialog box. Apply the following steps:
1. Drag and drop a PictureBox control, a Button control and OpenFileDialog
control on the form.
NOTES
2. Set the Text property of the button control to ‘Load Image File’.
3. Double-click the Load Image File button and modify the code of the Click
event as given below:
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
If OpenFileDialog1.ShowDialog <> Windows.Forms.
DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile (OpenFileDialog1.
FileName)
End If
End Sub
Output:
Click on the Load Image File button to load an image stored on your computer.
Self-Instructional
Material 23
Lab: Visual Basic FontDialog: It displays a dialog box that enables users to set a font and its attribute.
Programming
NOTES
It prompts the user to choose a font from among those installed on the local
computer and lets the user select the font, font size, and color. It returns the Font
and Color objects.
By default, the Color ComboBox is not shown on the Font dialog box. You
should set the ShowColor property of the FontDialog control to be True.
Consider an example to change the font and color of the text from a rich
text control using the Font dialog box. Apply the following steps:
1. Drag and drop a RichTextBox control, a Button control and a FontDialog
control on the form.
2. Set the Text property of the button control to ‘Change Font’.
Self-Instructional
24 Material
3. Set the ShowColor property of the FontDialog control to True. Lab: Visual Basic
Programming
4. Double-click the Change Color button and modify the code of the Click
event as given below:
Private Sub Button1_Click(sender As Object, e As EventArgs) NOTES
Handles Button1.Click
If FontDialog1.ShowDialog <> Windows.Forms.
DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
End Sub
Output:
The output obtained when the application is compiled and run using Start button
available at the Microsoft Visual Studio tool bar will be:
Self-Instructional
Material 25
Lab: Visual Basic In the Font dialog box, choose a font and a color, and then press the OK
Programming
button. The font and color selected will be added as the font and foreground color
of the text in the Rich text frame.
NOTES
Consider an example to save the text entered into a rich text box by the
user using the save file dialog box. Apply the following steps:
1. Drag and drop a Label control, a RichTextBox control, a Button control
and a SaveFileDialog control on the form.
2. Set the Text property of the label and the button control to ‘We
appreciate your comments’ and ‘Save Comments’, respectively.
3. Double-click the Save Comments button and modify the code as given
below:
Self-Instructional
26 Material
Private Sub Button1_Click(sender As Object, e As EventArgs) Lab: Visual Basic
Handles Button1.Click Programming
Self-Instructional
Material 27
Lab: Visual Basic Consider an example to change the forecolor of a label control using the
Programming
color dialog box. Apply the following steps:
1. Drag and drop a label control, a button control and a ColorDialog control
on the form.
NOTES
2. Set the Text property of the label and the button control to ‘Give me a
new Color’ and ‘Change Color’, respectively.
3. Change the font of the label as per your likings.
4. Double-click the Change Color button and modify the code of the Click
event as given below.
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
If C o lor Di a l og 1. Sh ow Di al og <> Win dow s. Fo rms.
DialogResult.Cancel Then
Label1.ForeColor = ColorDialog1.Color
End If
End Sub
When the application is compiled and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following output window.
Clicking on the Change Color button, the color dialog appears, select a
color and click the OK button. The selected color will be applied as the forecolor
of the text of the label.
PrintDialog: It displays a dialog box that enables users to select a printer
and set its attributes. There are various other controls related to printing of
documents. Let us have a brief look at these controls and their purpose.
1. PrintDocument control: It provides support for actual events and
operations of printing in Visual Basic and sets the properties for printing.
2. PrinterSettings control: It is used to configure how a document is
printed by specifying the printer.
3. PageSetUpDialog control: It allows the user to specify page-related
print settings including page orientation, paper size and margin size.
Self-Instructional
28 Material
4. PrintPreviewControl control: It represents the raw preview part of Lab: Visual Basic
Programming
print previewing from a Windows Forms application, without any dialog
boxes or buttons.
5. PrintPreviewDialog control: It represents a dialog box form that
NOTES
contains a PrintPreviewControl for printing from a Windows Forms
application.
Self-Instructional
Material 29
Lab: Visual Basic If PrintDialog1.ShowDialog = DialogResult.OK Then
Programming
PrintDocument1.PrinterSettings = PrintDialog1.
PrinterSettings
PrintDocument1.Print()
NOTES
End If
End Sub
When the application is compiled and run using Start button available at the
Microsoft Visual Studio tool bar, the output produced will be:
BLOCK 3
Self-Instructional
32 Material
The example code given below draggs a different type of data and provides Lab: Visual Basic
Programming
support for both cutting and copying. For these just add two picturebox controls
and write the code given below:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As _ NOTES
System.EventArgs) Handles MyBase.Load
‘Enable dropping.
PictureBox2.AllowDrop = True
End Sub
Self-Instructional
34 Material
Lab: Visual Basic
Programming
NOTES
Database Management
Database means a place where data can be stored in a structured manner. It is a
shared collection or batch of data that is logically related, along with their
descriptions designed to meet the information requirements of an organization.
Database Management System (DBMS) is a software system that allows
users to not only define and create a database but also maintain it and control its
access. A database management system can be called a collection of interrelated
data (usually called database) and a collection or set of programs that helps in
accessing, updating and managing that data (which form part of a database
management system).
The primary benefit of using a DBMS is to impose a logical and structured
organization on data. A DBMS provides simple mechanisms for processing huge
volumes of data because it is optimized for operations of this type. The two basic
operations performed by the DBMS are as follows:
1. Management of data in the database
2. Management of users associated with the database
Management of the data means specifying how data will be stored, structured
and accessed in the database. This includes the following:
Defining: Specifying data types and structures, and constraints for data
to be stored.
Constructing: Storing data in a storage medium.
Manipulating: Involves querying, updating and generating reports.
Sharing: Allowing multiple users and programs to access data
simultaneously.
Further, the database management system must offer safety and security of
the information stored, in case unauthorized access is attempted or the system
crashes. If data is required to be shared among many users, the system must
Self-Instructional
ensure that possible anomalous results are avoided. Material 35
Lab: Visual Basic Management of database users means managing the users in such a way
Programming
that they are able to perform any desired operations on the database. A DBMS
also ensures that a user cannot perform any operation for which he is not authorized.
In short, a DBMS is a collection of programs performing all necessary
NOTES
actions associated with a database. There are many DBMSs available in the market,
such as MySQL, Sybase, Oracle, MongoDB, Informix, PostgreSQL, SQL Server
etc.
How to Create Active X Control
ActiveX Controls were previously known as OLE controls. To render web pages
more interactive, an ActiveX control can be put on web pages. Much like you put
a Java applet on a page on the internet. To bring advanced features to the user
experience, app developers have used ActiveX controls on their web pages.
Program 3.2: To create an ActiveX control that will show a simple user interface
and accept input from a web page. Following are the steps for creating an ActiveX
control.
1. Create an assembly (class library project) containing an item of type User
Control.
2. Expose an interface for the control.
3. Embed the user control into a web page.
4. Transfer data from a web form to the control and display the data on the
control.
First, we will create a simple ActiveX control to get an overall idea about
how to create ActiveX controls.
Step 1: Create an assembly
Create a new project of type Class Library. Name the class library ActiveXDotNET.
Self-Instructional
36 Material
Delete the Class1.cs file from your project once the project is developed, Lab: Visual Basic
Programming
as it won’t be required. Next, by right-clicking the project in your Solution Explorer,
add User Control to the project, select Add, then User Control. Name your control
as “myControl”.
NOTES
On the user control, add some UI elements, and a text box control named
txtUserText. The txtUserText control will display the user data that is typed into
the web form. This will demonstrate how to pass data to your User Control.
When you are done adding your user interface to the control we now have
to add a key element to the control, an Interface. The interface will allow COM/
COM+ objects to know what properties they can use. In this case, we are going
to expose one public property named UserText. That property will allow us to set
the value of the text box control.
Step 2: Expose the interface for the control
First, create a private String to hold the data passed from the web form to the
control:
private Dim mStr_UserText as String
Place this String just inside the Class myControl.
Next, we will create a public property. The web page will use this property
to pass text back to your control. This property will allow reading and writing of
the value mStr_UserText.
Public Property UserText() As [String]
Get
Return mStr_UserText
End Get
Set(ByVal Value As [String])
mStr_UserText = value
‘Update the text box control value also.
txtUserText.Text = value
End Set
Self-Instructional
Material 37
Lab: Visual Basic End Property
Programming
In this example, you will note the extra code in the set section of the public property.
We will set the private String value equal to the value passed to the property when
NOTES a value is passed from the web form to the control. We are simply going to modify
the value of the Text Box control directly. Typically you would not do this. Instead,
you would raise an event and then validate the data being passed by examining the
private variable mStr_UserText. Then you would set the value of the Text Box
Control. However, it would add significant code to this example and for simplicity
sake we are omitting that security precaution.
Now, you have a public property that .NET assemblies can use, you need
to make that property available to the COM world. This can be done by creating
an interface and making the myControl class inherit the interface. It allows COM
objects to see what properties are made available. Now, the code will be:
Namespace ActiveX.NET
{
Public Interface AxMyControl
Property UserText() As String
End Property
End Interface ‘AxMyControl
Public Class myControl
Inherits System.Windows.Forms.UserControl, AxMyControl
Private mStr_UserText As [String]
Public Property UserText() As String
Get
Return mStr_UserText
End Get
Set(ByVal Value As String)
mStr_UserText = value
‘Update the text box control value also.
txtUserText.Text = value
End Set
End Property
End Class ‘myControl
Notice that, we have an interface defined. The interface tells COM/COM+
that there is a public property available for use that is of type String and is readable
(get) and writeable (set). All we do now is have the Class myControl inherit the
interface and viola! We have a .NET assembly that acts like an ActiveX Control.
Self-Instructional
38 Material
Step 3: Embed the user control in a web page Lab: Visual Basic
Programming
The last thing we do now is use the control in an example web page.
<html>
<body color=white> NOTES
<hr>
<font face=arial size=1>
<OBJECT id=”myControl1" name=”myControl1"
classid=”ActiveX.NET.dll#ActiveXDotNET.myControl”width=288
height=72>
</OBJECT>
</font>
<form name=”frm” id=”frm”>
<input type=”text” name=”txt” value=”enter text
here”><input type=button value=”Click me”onClick=”doScript();”>
</form>
<hr>
</body>
<script language=”javascript”>
function doScript()
{
myControl1.UserText = frm.txt.value;
}
</script>
</html>
You will notice in the HTML code above, that you call your .NET assembly
very similar to an ActiveX control; however there is no GUID, and no .OCX file.
Your CLASSID is now the path to your DLL and the Namespace.Classname
identifier. Refer to the code above to understand the syntax of the CLASSID
object tag property. Place the HTML file and your DLL in the same directory on
your web server and navigate to the HTML document. (Do not load the HTML
document by double clicking on it, navigate to it in your browser by using the Fully
Qualified URL.) *NOTE: You might need to add your web server to your Trusted
Sites list in your Internet Explorer browser.
Step 4: Transfer data from the web form to the user control
When you load the HTML page, your control should load into the page and you
will see a web form with a text box and a button. In this example, if you type some
text into the text box and click the button, it will use JavaScript to send the text
from the web page form, to the User Control that you just built. Your User Control
will then display the text in the Text Box control that I on the form.
Self-Instructional
Material 39
Lab: Visual Basic Program 3.3 Another program of ActiveX control.
Programming
Step 1: Create an assembly
First, you create a new project of type Class Library. Name the class library
NOTES ActiveXDotNET.
Once the project is created, delete the Class1.cs file from your project as it
will not be necessary. Next, add a User Control to the project by right clicking on
the project in your solution explorer, choose Add, then User Control. Name your
user control myControl.
On the user control, add some UI elements, and a text box control named
txtUserText. The txtUserText control will display the user data that is typed into
the web form. This will demonstrate how to pass data to your User Control.
When you are done adding your user interface to the control we now have
to add a key element to the control, an Interface. The interface will allow COM/
COM+ objects to know what properties they can use. In this case, we are going
to expose one public property named UserText. That property will allow us to set
the value of the text box control.
Step 2: Expose the Interface for the control
First, create a private String to hold the data passed from the web form to the
control:
private String mStr_UserText;
Self-Instructional Place this String just inside the Class myControl.
40 Material
Next, we will create a public property. The web page will use this property Lab: Visual Basic
Programming
to pass text back to your control. This property will allow reading and writing of
the value mStr_UserText.
public String UserText {
NOTES
get {
return mStr_UserText;
}
set {
mStr_UserText = value;
//Update the text box control value also.
txtUserText.Text = value;
}
}
In this example, you will note the extra code in the set section of the public
property. When a value is passed from the web form to the control we will set the
private String value equal to the value passed to the property. In addition, we are
simply going to modify the value of the Text Box control directly. Typically you
would NOT do this. Instead, you would raise an event and then validate the data
being passed by examining the private variable mStr_UserText. Then you would
set the value of the Text Box Control. However, that would add significant code to
this example and for simplicity sake we are omitting that security precaution.
Now that you have a public property that .NET assemblies can use, you
need to make that property available to the COM world. We do this by creating
an Interface and making the myControl class inherit the interface. This will allow
COM objects to see what properties we have made available.
Your code will now look like this:
namespace ActiveXDotNET {
public interface AxMyControl {
String UserText {
set;
get;
}
}
public class myControl: System.Windows.Forms.UserControl,
AxMyControl {
private String mStr_UserText;
public String UserText {
get {
return mStr_UserText;
Self-Instructional
Material 41
Lab: Visual Basic }
Programming
set {
mStr_UserText = value;
//Update the text box control value also.
NOTES
txtUserText.Text = value;
}
}
Notice that we now have an interface defined, the interface tells COM/
COM+ that there is a public property available for use that is of type String and is
readable (get) and writeable (set). All we do now is have the Class myControl
inherit the interface and viola! We have a .NET assembly that acts like an ActiveX
Control.
Step 3: Embed the user control in a web page
The last thing we do now is use the control in an example web page.
<html>
<body color=white>
<hr>
<font face=arial size=1>
<OBJECT id=”myControl1" name=”myControl1"
classid=”ActiveX.NET.dll#ActiveX.NET.myControl” width=288
height=72>
</OBJECT>
</font>
<form name=”frm” id=”frm”>
<input type=”text” name=”txt” value=”enter text
here”><input type=button value=”Click me”
onClick=”doScript();”>
</form>
<hr>
</body>
<script language=”javascript”>
function doScript()
{
myControl1.UserText = frm.txt.value;
}
</script>
</html>
Self-Instructional
42 Material
You will notice in the HTML code above, that you call your .NET assembly Lab: Visual Basic
Programming
very similar to an ActiveX control; however there is no GUID, and no .OCX file.
Your CLASSID is now the path to your DLL and the Namespace.Classname
identifier. Refer to the code above to understand the syntax of the CLASSID
object tag property. Place the HTML file and your DLL in the same directory on NOTES
your web server and navigate to the HTML document. (Do not load the HTML
document by double clicking on it, navigate to it in your browser by using the Fully
Qualified URL.) *NOTE: You might need to add your web server to your Trusted
Sites list in your Internet Explorer browser.
Step 4: Transfer data from the web form to the user control
When you load the HTML page, your control should load into the page and you
will see a web form with a text box and a button. In this example, if you type some
text into the text box and click the button, it will use JavaScript to send the text
from the web page form, to the User Control that you just built. Your User Control
will then display the text in the Text Box control that I on the form.
Database Object (DAO) and Properties
DAO pattern or Data Access Object pattern is used to separate low level data
accessing API or operations from high level business services. The participants in
Data Access Object Pattern are as follows.
1. DAO Interface: It defines the standard operations to be performed on a
model object(s).
2. DAO Concrete Class: It is responsible to get data from a data source.
3. Model or Value Object: It is simple POJO containing get/set methods to
store data retrieved using DAO class.
When it comes to implementing a data access solution in your VB
applications, you currently have three choices: Data Access Objects (DAO),
Remote Data Objects (RDO), and ActiveX Data Objects (ADO).
DAO was created before RDO and ADO, is a set of objects that enables
client applications to programmatically access data. DAO not only allows you to
access data but also helps in controling and managing local and remote databases
in different formats. DAO can be used create and modify the database structure;
create tables, queries, relationships, and indexes; retrieve, add, update, and remove
data; implement security; work with different file formats; and link tables to other
tables.
Implementation
Program 3.4: We are going to create a Student object acting as a Model or Value
Object. StudentDao is Data Access Object Interface.StudentDaoImpl is concrete
class implementing Data Access Object Interface. DaoPatternDemo, our demo
class, will use StudentDao to demonstrate the use of Data Access Object pattern.
Self-Instructional
Material 43
Lab: Visual Basic
Programming
NOTES
Self-Instructional
44 Material
Step 2: Create Data Access Object Interface. Lab: Visual Basic
Programming
import java.util.List;
public interface StudentDao
{ NOTES
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
Step 3: Create concrete class implementing above interface.
public class DaoPatternDemo
{
public static void main(String[] args)
{
StudentDao studentDao = new StudentDaoImpl();
//update student
Student student =studentDao.getAllStudents().get(0);
student.setName(“Michael”);
studentDao.updateStudent(student);
}
}
Step 4: Use the StudentDao to demonstrate Data Access Object pattern usage.
public class DaoPatternDemo {
public static void main(String[] args) {
Self-Instructional
Material 45
Lab: Visual Basic StudentDao studentDao = new StudentDaoImpl();
Programming
//print all students
for (Student student : studentDao.getAllStudents()) {
S yst em. ou t .p ri n tl n ( “S t u d en t : [Ro llN o : “ +
NOTES
student.getRollNo() + “, Name : “ + student.getName() + “ ]”);
}
//update student
Student student =studentDao.getAllStudents().get(0);
student.setName(“Michael”);
studentDao.updateStudent(student);
//get the student
studentDao.getStudent(0);
S yst em. ou t .p ri n tl n ( “S t u d en t : [Ro llN o : “ +
student.getRollNo() + “, Name : “ + student.getName() + “ ]”);
}
}
Step 5: Verify the output.
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]
DAO objects
Let us have a look at the DAO objects to understand DAO better.
Table 3.1 Names and descriptions of common DAO objects
Self-Instructional
46 Material
The DBEngine is the highest-level object in the DAO object model. It Lab: Visual Basic
Programming
contains all other objects and collections. The Database object is the member of
the Databases collection of the default Workspace object, which is a member of
the Workspaces collection of the DBEngine object.
NOTES
Program 3.5: Let’s create a simple VB project to access the data stored in
Microsoft’s sample Northwind database to demonstrate how you might put DAO
to work.
1. Open VB and start a new project.
2. Go to Project References and select Microsoft DAO 3.6 Object Library
(depending on the version of VB you are using), as shown in Figure given
below.
Self-Instructional
48 Material
Set dbJet = Nothing Lab: Visual Basic
Programming
Set wrkJet = Nothing
End Sub
Add the following code to the Private SubcmdGetDataODBCDirect NOTES
_Click() event.
Private Sub cmdGetDataODBCDirect_Click()
Dim wrkJet As DAO.Workspace, wrkODBC As DAO.Workspace
Dim conODBCDirect As DAO.Connection
Dim rsODBCDirect As DAO.Recordset
Dim strConn As String
‘connection string for
strConn = “ODBC;DATABASE=employee_records;
UID=admin;PWD=sql;DSN=employee”
Self-Instructional
Material 49
Lab: Visual Basic ‘close recordset
Programming
rsODBCDirect.Close
End If
End With
NOTES
‘close workspace
wrkODBC.Close
‘release objects
Set rsODBCDirect = Nothing
Set wrkODBC = Nothing
Set conODBCDirect = Nothing
End Sub
3. Modify strLocation to reflect the location of the Northwind database on
your computer or use another .mdb database and modify Set dbJet =
wrkJet.OpenDatabase(strLocation & “Northwind.mdb”) to reflect the name
of the database.
4. Modify strConn to reflect the DSN name, password, and UID of a remote
database.
5. Modify the query in Set rsODBCDirect = conODBCDirect.OpenRecordset
(“SELECT LastName FROM Employees”, dbOpenDynamic) to reflect
the query you’d like to run.
6. Press [Ctrl][F5] to run the project.
7. Click the Get Data Jet button and the Get Data ODBC Direct button to
obtain data using Microsoft Jet and ODBCDirect, respectively.
8. You will observe a screen as shown below:
Program 3.6: To create a new Database object and opens an existing Database
object in the default Workspace objects. Then it enumerates the Database collection
and the Properties collection of each Database object.
Sub DatabaseObjectX()
Dim wrkAcc As Workspace
Dim dbsNorthwind As Database
Dim dbsNew As Database
Dim dbsLoop As Database
Dim prpLoop As Property
Self-Instructional
Material 51
Lab: Visual Basic Set wrkAcc = CreateWorkspace(“AccessWorkspace”, “admin”, _
Programming
“”, dbUseJet)
‘ Make sure there isn’t already a file with the name of
‘ the new database.
NOTES
If Dir(“NewDB.mdb”) <> “” Then Kill “NewDB.mdb”
Self-Instructional
52 Material
‘ Make sure there isn’t already a file with the name of Lab: Visual Basic
the new database. Programming
Database Access
Applications access the database to retrieve and display the data stored and also
to insert, update and delete data in the database. Microsoft ActiveX Data
Objects.NET (ADO.NET) is a model that is used to access and update data from
.NET applications.
Self-Instructional
Material 53
Lab: Visual Basic ADO.NET Object Model
Programming
It is nothing but the structured process flow through various components. Data
provider is used to retrieve the data residing in the database. The object model
NOTES can be pictorially described as given below:
Self-Instructional
54 Material
Lab: Visual Basic
Programming
NOTES
2. Select the server name and database name in the Add Connection dialog
box.
Self-Instructional
Material 55
Lab: Visual Basic 3. Click on the Test Connection button to check for the connection succeeded.
Programming
NOTES
Self-Instructional
56 Material
7. Select Database as the data source type Lab: Visual Basic
Programming
NOTES
Self-Instructional
Material 57
Lab: Visual Basic 9. Choose the connection already set up.
Programming
NOTES
Self-Instructional
58 Material
11. Choose the database object that is Customers table in our example and Lab: Visual Basic
Programming
then click the Finish button.
NOTES
12. Select the Preview Data link to see the data in the Results grid as shown
below.
Self-Instructional
Material 59
Lab: Visual Basic It will produce the following output when you run the application using Start
Programming
button available at the Microsoft Visual Studio tool bar.
NOTES
Self-Instructional
60 Material
All previously defined connections are listed with their properties in this Lab: Visual Basic
Programming
window. You have to click on New button to add a new connection. The following
screenshot shows the main OLE DB connection configuration form.
NOTES
When, we click on the Provider drop-down list, all available data sources
providers will be displayed as shown below:
Self-Instructional
Material 61
Lab: Visual Basic Following are the main OLE DB connection properties:
Programming
1. Provider: It is used to connect to the data source.
2. Server name: The Server that you want to connect with.
NOTES 3. Authentication type: It includes security parameters used to establish the
connection.
4. Database name: The database name that we want to connect with.
Generally, OLE DB connection manager is used in all tasks and components
used to connect to an external database such as:
Execute SQL Task
Execute T-SQL Task
OLE DB Source
OLE DB Destination
OLE DB command
Look up Transformation
ODBC connection manager
ODBC (Open Database Connectivity) is a standard API used to access
database.It provides access only to relational databases which are used by OLE
DB to access SQL-based data sources.
ODBC SSIS connection managers are also popular which are used when
data sources are defined as DSN (Database Source Name) in the operating system.
Right-click inside the connection manager tab panel to add an ODBC
connection manager. Click on New Connection button as shown below:
Self-Instructional
62 Material
This form contains all ODBC connections added earlier. Click on New Lab: Visual Basic
Programming
button to add a new one. The following screenshot shows the ODBC connection
manager configuration form.
NOTES
When, we click on the Provider drop-down list, all available data sources
providers will be displayed as shown below.
Connection should be closed and release the resources once the use of
database is over. The Close() method is used to close the Database Connection.
It rolls back any pending transactions and releases the connection from the database
connected by the ODBC Data Provider. The code for ADO.NET ODBC
connection will be:
Imports System.Data.Odbc
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OdbcConnection
connetionString = “Driver={Microsoft Access Driver
(*.mdb)};DBQ=yourdatabasename.mdb;”
cnn = New OdbcConnection(connetionString)
Try
Self-Instructional
Material 63
Lab: Visual Basic cnn.Open()
Programming
MsgBox(“Connection Open ! “)
cnn.Close()
Catch ex As Exception
NOTES
MsgBox(“Can not open connection ! “)
End Try
End Sub
End Class
BLOCK 4
We will work with SQL Server, the default provider for .NET. We’ll be
displaying data from Customers table in sample Northwind database in SQL Server.
It requires establishing a connection to this database. You need to right-click on
the Data Connections icon in Server Explorer and select Add Connection item
that opens the Data Link Properties dialog. It allows us to enter the name of the
server with which we want to work along with login name and password as shown
below.
Now select Northwind database from the list. After that click on the Test
Connection tab, If the connection is successful, a message “Test Connection
Succeeded” is displayed. Click OK and close the Data Link Properties or add
connection when connection to the database is set. It displays the Tables, Views
and Stored Procedures in that Northwind sample database when you expand the
Self-Instructional
Material 65
Lab: Visual Basic connection node that is (“+” sign). Expanding the Tables node will display all the
Programming
tables available in the database.
NOTES
We will work with Customers table to display its data in our example. Now,
drag Customers table onto the form from the Server Explorer. It creates
SQLConnection1 and SQLDataAdapter1 objects that are the data connection
and data adapter objects used to work with data. They are displayed on the
component tray. After that, generate the dataset which holds data from the data
adapter. To do that select Data’!Generate DataSet from the main menu or rightclick
SQLDataAdapter1 object and select generate DataSet menu. It will displays the
generate Dataset dialogbox.
Select the radio button with New option to create a new dataset once the
dialogbox is displayed. Make sure Customers table is checked and click OK. It
adds a dataset, DataSet to the component tray. After that, drag a DataGrid from
toolbox to display Customers table. Set the data grid’s DataSource property to
DataSet and it’s DataMember property to Customers. Next, we need to fill the
dataset with data from the data adapter. The code for that is given below:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs)_
Handles MyBase.Load
DataSet.Clear()
SqlDataAdapter1.Fill(DataSet)
‘filling the dataset with the dataadapter’s fill method
End Sub
The output of the above code is given below:
Customers table is displayed in the data grid once the application is executed.
That’s one of the simplest ways of displaying data using the Server Explorer window.
Self-Instructional
66 Material
Microsoft Access and Oracle Database Lab: Visual Basic
Programming
You need to select Microsoft OLE DB Provider for Oracle from the Provider tab
in the DataLink dialog when working with Oracle. The process is same when
working with Oracle or MS Access but has some minor changes. It requires
NOTES
appropriate Username and password.
Self-Instructional
68 Material
Catch e As Exception Lab: Visual Basic
Programming
End Try
End Sub
End Class
NOTES
The above code displays records from discounts table in MessageBoxes.
Retrieving records with a Console Application
Imports System.Data.SqlClient
Imports System.Console
Module Module1
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Sub Main()
Try
myConnection = New
SqlConnection(“server=localhost;uid=sa;pwd=;database=pubs”)
‘you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand(“Select * from discounts”,
myConnection)
dr = myCommand.ExecuteReader
Do
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
‘ writing to console
End While
Loop While dr.NextResult()
Catch
End Try
dr.Close()
myConnection.Close()
End Sub
End Module
Self-Instructional
Material 69
Lab: Visual Basic Inserting Records
Programming
Example 4.2: To insert a Record into the Jobs table in Pubs sample database.
Imports System.Data.SqlClient
NOTES Public Class Form2 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
‘integer holds the number of records inserted
Private Sub Form2_Load(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e_As System.EventArgs) Handles Button1.Click
myConnection = New SqlConnection(“server=localhost;
uid=sa;pwd=;database=pubs”)
‘you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand(“Insert into Jobs values 12,’IT
Manager’,100,300,_
myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show(“New Row Inserted” & ra)
myConnection.Close()
End Sub
End Class
Deleting a Record
Example 4.3: For deleting a record, we will use Authors table in Pubs sample
database to work with this code. Drag a button onto the form and place the
following code.
Imports System.Data.SqlClient
Public Class Form3 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
Private Sub Form3_Load(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles MyBase.Load
Self-Instructional End Sub
70 Material
Private Sub Button1_Click(ByVal sender As System.Object, Lab: Visual Basic
ByVal e_ Programming
Updating Records
Example 4.4: For updating a record, we will update a row in Authors table. Drag
a button onto the form and write the following code.
Imports System.Data.SqlClient
Public Class Form4 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
Private Sub Form4_Load(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles Button1.Click
myConnection = New
SqlConnection(“server=localhost;uid=sa;pwd=;database=pubs”)
‘you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand(“Update Authors Set
city=’Oakland’
where city=_
‘San Jose’ “,myConnection) Self-Instructional
Material 71
Lab: Visual Basic ra=myCommand.ExecuteNonQuery()
Programming
MessageBox.Show(“Records affected” & ra)
myConnection.Close()
End Sub
NOTES
End Class
Self-Instructional
Material 73
Lab: Visual Basic System.EventArgs) Handles Button1.Click
Programming
myConnection = New
OleDbConnection(“”Provider=MSDAORA.1;User_
ID=scott;password=tiger;database=ora”
NOTES
)
Try
myConnection.Open()
myCommand = New OleDbCommand(“Insert into emp values
12,’Ben’,’Salesman’,300
12-10-2001,3000,500,10 “, myConnection)
‘emp table has 8 columns. You can work only with the
columns you want
ra=myCommand.ExecuteNonQuery()
MessageBox.Show(“Records Inserted” & ra)
myConnection.Close()
Catch
End Try
End Sub
End Class
Updating Records
Program 4.7: Drag a Button on a new form and write the following code.
Imports System.Data.OleDb
Public Class Form4 Inherits System.Windows.Forms.Form
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim ra as Integer
Private Sub Form4_Load(ByVal sender As System.Object,
ByVal e As_
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles Button1.Click
Try
myConnection = New OleDbConnection(“”Provider=
MSDAORA.1;User_
ID=scott;password=tiger;database=ora”)
myConnection.Open()
Self-Instructional
74 Material
myCommand = New OleDbCommand(“Update emp Set DeptNo=65 Lab: Visual Basic
Programming
where DeptNo=793410",_ myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show(“Records Updated” & ra)
NOTES
myConnection.Close()
Catch
End Try
End Sub
End Class
Deleting Records
Program 4.8: Drag a Button on a new form and write the following code.
Imports System.Data.OleDb
Public Class Form3 Inherits System.Windows.Forms.Form
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim ra as Integer
Private Sub Form3_Load(ByVal sender As System.Object,
ByVal e As_
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e_
As System.EventArgs) Handles Button1.Click
Try
myConnection = New OleDbConnection(“”Provider=MSDAORA.
1;User_
ID=scott;password=tiger;database=ora”)
myConnection.Open()
myCommand = New OleDbCommand(“Delete from emp where
DeptNo=790220",_
myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show(“Records Deleted” & ra)
myConnection.Close()
Catch
End Try
End Sub
End Class
Self-Instructional
Material 75
Lab: Visual Basic Data Access using MSAccess
Programming
Program 4.9: In this program, create a database named Emp in Microsoft Access
in the C drive of your computer. In the Emp database, create a table, Table1 with
NOTES EmpNo, EName and Department as columns, insert some values in the table and
close it. Drag three TextBoxes and a Button. The following code will assume that
TextBox1 is for EmpNo, TextBox2 is for EName and TextBox3 is for Department.
Our intention is to retrieve data from Table1 in the Emp Database and display the
values in these TextBoxes without binding, when the Button is clicked.
Imports System.Data.OleDb
Public Class Form1 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e as _
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As_
System.EventArgs) Handles Button1.Click
Try
cn = New OleDbConnection(“Provider=Microsoft.
Jet.OLEDB.4.0;_
Data Source=C:\emp.mdb;”)
‘provider to be used when working with access database
cn.Open()
cmd = New OleDbCommand(“select * from table1”, cn)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr(0)
TextBox2.Text = dr(1)
TextBox3.Text = dr(2)
‘ loading data into TextBoxes by column index
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
Self-Instructional End Class
76 Material
When you run the code and click the Button, records from Table1 of the Lab: Visual Basic
Programming
Emp database will be displayed in the TextBoxes.
Program 4.10: Write a code for retrieving records with a Console Application.
Imports System.Data.OleDb NOTES
Imports System.Console
Module Module1
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Sub Main()
Try
cn = New OleDbConnection(“Provider=Microsoft.
Jet.OLEDB.4.0;Data
Source=C:\emp.mdb;_
Persist Security Info=False”)
cn.Open()
cmd = New OleDbCommand(“select * from table1”, cn)
dr = cmd.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
‘writing to console
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Module
BLOCK 5
SIMPLE APPLICATION DEVELOPMENT
Self-Instructional
78 Material
7. Pay roll processing Lab: Visual Basic
Programming
8. Personal information system
9. Question database and conducting Quiz
10. Personal diary NOTES
1. Library Information System
Add Books:
Public Class AddBooks
Public NameFrm, NameTo As String
Private Sub Button9_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button9.Click
Me.Close()
End Sub
End Try
End Sub
Sub generateyear()
Dim YearNow As Integer
Self-Instructional
Material 79
Lab: Visual Basic YearNow = Int(My.Computer.Clock.LocalTime.Year.ToString)
Programming
Dim a, b, c As Integer
a = YearNow - 5
b = YearNow
NOTES
For c = a To b
ComboBox2.Items.Add(c)
Next
End Sub
Private Sub ComboBox1_LostFocus(ByVal sender As Object,
ByVal e As System.EventArgs) Handles ComboBox1.LostFocus
ComboBox1.Text = ComboBox1.Text.ToUpper()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
ComboBox3.Text = “Available”
Call enablethem()
End Sub
Private Sub TextBox2_LostFocus(ByVal sender As Object,
ByVal e As System.EventArgs) Handles TextBox2.LostFocus
NameFrm = TextBox2.Text
Call Sentence()
TextBox2.Text = NameTo
End Sub
Sub disablethem()
‘TextBox1.Enabled = False
TextBox2.Enabled = False
TextBox3.Enabled = False
ComboBox1.Enabled = False
TextBox4.Enabled = False
TextBox5.Enabled = False
TextBox6.Enabled = False
ComboBox2.Enabled = False
ComboBox3.Enabled = False
End Sub
Sub enablethem()
TextBox1.Enabled = True
TextBox2.Enabled = True
TextBox3.Enabled = True
Self-Instructional
80 Material
ComboBox1.Enabled = True Lab: Visual Basic
Programming
TextBox4.Enabled = True
TextBox5.Enabled = True
TextBox6.Enabled = True
NOTES
ComboBox2.Enabled = True
ComboBox3.Enabled = True
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
ComboBox1.Text = “”
ComboBox2.Text = “”
ComboBox3.Text = “”
End Sub
Sub Sentence()
Dim a, b As Integer
a = NameFrm.Length
NameTo = “”
For b = 0 To a - 1
If b = 0 Then
If Char.IsLower(NameFrm(0)) Then
NameTo = Char.ToUpper(NameFrm(0))
Else
NameTo = NameFrm(0)
End If
Else
If NameFrm(b - 1) = “ “ Then
NameTo = NameTo + Char.ToUpper(NameFrm(b))
Else
NameTo = NameTo + NameFrm(b)
End If
End If
Next
End Sub
Private Sub TextBox3_LostFocus(ByVal sender As Object,
ByVal e As System.EventArgs) Handles TextBox3.LostFocus
Self-Instructional
Material 81
Lab: Visual Basic NameFrm = TextBox3.Text
Programming
Call Sentence()
TextBox3.Text = NameTo
End Sub
NOTES
Private Sub TextBox3_TextChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TextBox3.TextChanged
End Sub
Private Sub TextBox4_LostFocus(ByVal sender As Object,
ByVal e As System.EventArgs) Handles TextBox4.LostFocus
NameFrm = TextBox4.Text
Call Sentence()
TextBox4.Text = NameTo
End Sub
Private Sub TextBox4_TextChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TextBox4.TextChanged
End Sub
Private Sub TextBox5_LostFocus(ByVal sender As Object,
ByVal e As System.EventArgs) Handles TextBox5.LostFocus
NameFrm = TextBox5.Text
Call Sentence()
TextBox5.Text = NameTo
End Sub
Private Sub TextBox5_TextChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TextBox5.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
If TextBox1.Text = “” Then
MsgBox(“Please enter the Book ID!”, 0, “”)
Else
Try
If objcon.State = ConnectionState.Closed Then objcon.Open()
com = New OleDb.OleDbCommand(“INSERT INTO Books VALUES(‘“
& TextBox1.Text & “‘,’” & ComboBox1.Text & “‘,’” & TextBox2.Text
& “‘,’” & TextBox3.Text & “‘,’” & TextBox4.Text & “‘,’” &
ComboBox2.Text & “‘,’” & TextBox5.Text & “‘,’” & TextBox6.Text
& “‘,’” & ComboBox3.Text & “‘)”, objcon)
com.ExecuteNonQuery()
Self-Instructional Call readData()
82 Material
MsgBox(“Saved successfully”, 0, “SUCCESS”) Lab: Visual Basic
Programming
objcon.Close()
Catch ex As Exception
MsgBox(ex.Message, 0, “”)
NOTES
End Try
End If
End Sub
Sub readData()
ListView1.Clear()
ListView1.Columns.Add(“BOOK ID”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“GROUP ID”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“BOOK NAME”, 310,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PUBLISHER”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“AUTHOR”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Ad d(“ PUBL ISHIN G YE AR”, 130,
HorizontalAlignment.Center)
ListView1.Columns.Add(“EDITION”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PRICE”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“STATUS”, 90,
HorizontalAlignment.Center)
ListView1.View = View.Details
Try
If (objcon.State = ConnectionState.Closed) Then
objcon.Open()
com = New OleDb.OleDbCommand(“SELECT * FROM Books “,
objcon)
dr = com.ExecuteReader
While dr.Read()
Call adddatatolistview(ListView1, dr(0), dr(1), dr(2),
dr(3), dr(4), dr(5), dr(6), dr(7), dr(8))
End While
dr.Close()
objcon.Close()
Catch
Self-Instructional
Material 83
Lab: Visual Basic ‘MsgBox(“Please Refresh”, MsgBoxStyle.Information, “”)
Programming
End Try
End Sub
Public Sub adddatatolistview(ByVal lvw As ListView, ByVal
NOTES
BookID As String, ByVal GroupID As String, ByVal BookName As
String, ByVal Publisher As String, ByVal Author As String,
ByVal PubYear As String, ByVal edi As String, ByVal pric As
String, ByVal st As String)
Dim lv As New ListViewItem
lvw.Items.Add(lv)
lv.Text = BookID
lv.SubItems.Add(GroupID)
lv.SubItems.Add(BookName)
lv.SubItems.Add(Publisher)
lv.SubItems.Add(Author)
lv.SubItems.Add(PubYear)
lv.SubItems.Add(edi)
lv.SubItems.Add(pric)
lv.SubItems.Add(st)
End Sub
Private Sub Button8_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button8.Click
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
If MessageBox.Show(“Do you really want to delete?”,
“ARE YOU SURE”, MessageBoxButtons.YesNo) =
Windows.Forms.DialogResult.Yes Then
com = New OleDb.OleDbCommand(“DELETE FROM Books WHERE
BookID=’” & TextBox1.Text & “‘“, objcon)
com.ExecuteNonQuery()
objcon.Close()
MsgBox(“Deleted successfully”, 0, “SUCCESS”)
End If
Catch ex As Exception
End Try
End Sub
Sub fill_list()
com = New OleDb.OleDbCommand(“Select * from Books”,
Self-Instructional objcon)
84 Material
Dim dr As OleDb.OleDbDataReader Lab: Visual Basic
Programming
dr = com.ExecuteReader
dr.Read()
While (dr.NextResult)
NOTES
End While
End Sub
Private Sub GroupBox1_Enter(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles GroupBox1.Enter
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TextBox1.TextChanged
Dim i As Integer
ListView1.SelectedItems.Clear()
TextBox1.Focus()
Try
If Me.TextBox1.Text = “” Then
TextBox2.Text = “”
Else
For i = 0 To ListView1.Items.Count - 1
If TextBox1.Text = ListView1.Items(i).SubItems(0).Text
Then
ComboBox1.Text = ListView1.Items(i).SubItems(1).Text
TextBox2.Text = ListView1.Items(i).SubItems(2).Text
TextBox3.Text = ListView1.Items(i).SubItems(3).Text
TextBox4.Text = ListView1.Items(i).SubItems(4).Text
ComboBox2.Text = ListView1.Items(i).SubItems(5).Text
TextBox5.Text = ListView1.Items(i).SubItems(6).Text
TextBox6.Text = ListView1.Items(i).SubItems(7).Text
ComboBox3.Text = ListView1.Items(i).SubItems(8).Text
ListView1.Items(i).Selected = True
Exit For
End If
Next
End If
Catch
End Try
End Sub
Self-Instructional
Material 85
Lab: Visual Basic Private Sub ListView1_SelectedIndexChanged(ByVal sender
Programming As System.Object, ByVal e As System.EventArgs) Handles
ListView1.SelectedIndexChanged
Dim i As Integer
NOTES For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).Selected = True Then
TextBox1.Text = ListView1.Items(i).SubItems(0).Text
TextBox7.Clear()
Exit For
End If
Next
ListView1.Focus()
ListView1.FullRowSelect = True
End Sub
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
Call GroupNameCom()
End Sub
Sub GroupNameCom()
Try
Self-Instructional
86 Material
If objcon.State = ConnectionState.Closed Then Lab: Visual Basic
objcon.Open() Programming
End While
dr.Close()
objcon.Close()
Catch ex As Exception
End Try
End Sub
End Try
End Sub
End Class
Self-Instructional
Material 87
Lab: Visual Basic
Programming
NOTES
Book Details:
Public Class BookDetail
Dim sel As Integer
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
Label1.Text = ComboBox1.Text
Label1.Visible = True
If Label1.Text = “STATUS” Then
ComboBox2.Enabled = True
ComboBox2.Visible = True
TextBox1.Visible = False
Else
ComboBox2.Enabled = False
ComboBox2.Visible = False
TextBox1.Visible = True
End If
Call forselect()
End Sub
Sub forselect()
If ComboBox1.Text = “BOOK ID” Then
sel = 1
ElseIf ComboBox1.Text = “BOOK NAME” Then
sel = 2
ElseIf ComboBox1.Text = “AUTHOR” Then
sel = 3
Self-Instructional
88 Material
ElseIf ComboBox1.Text = “STATUS” Then Lab: Visual Basic
Programming
sel = 8
End If
End Sub
NOTES
Self-Instructional
Material 89
Lab: Visual Basic Call adddatatolistview(ListView1, dr(0), dr(1), dr(2),
Programming dr(3), dr(4), dr(5), dr(6), dr(7), dr(8))
End While
dr.Close()
NOTES
objcon.Close()
Catch
‘MsgBox(“Please Refresh”, MsgBoxStyle.Information, “”)
End Try
End Sub
Public Sub adddatatolistview(ByVal lvw As ListView, ByVal
BookID As String, ByVal GroupID As String, ByVal BookName As
String, ByVal publisher As String, ByVal author As String,
ByVal pubyear As String, ByVal edi As String, ByVal pric As
String, ByVal status As String)
Dim lv As New ListViewItem
lvw.Items.Add(lv)
lv.Text = BookID
lv.SubItems.Add(GroupID)
lv.SubItems.Add(BookName)
lv.SubItems.Add(publisher)
lv.SubItems.Add(author)
lv.SubItems.Add(pubyear)
lv.SubItems.Add(edi)
lv.SubItems.Add(pric)
lv.SubItems.Add(status)
End Sub
End Try
End Sub
Private Sub Button5_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button5.Click
Self-Instructional
Material 91
Lab: Visual Basic Try
Programming
Dim i As Integer
For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).Selected = True Then
NOTES
TextBox1.Text = ListView1.Items(i - 1).SubItems(0).Text
Exit For
End If
Next
ListView1.Focus()
ListView1.FullRowSelect = True
Catch ex As Exception
End Try
End Sub
End Class
Issue Book:
Public Class IssueBook
End Sub
Self-Instructional
92 Material
Private Sub IssueBook_Load(ByVal sender As System.Object, Lab: Visual Basic
ByVal e As System.EventArgs) Handles MyBase.Load Programming
Call Retrive_C()
Call BookID_Combo()
NOTES
Call readData()
End Sub
Sub Retrive_C()
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“Select CID from Customer”,
objcon)
dr = com.ExecuteReader
While dr.Read
ComboBox5.Items.Add(dr.Item(0))
End While
dr.Close()
objcon.Close()
Catch ex As Exception
End Try
End Sub
Sub BookID_Combo()
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“Select BookID from Books
WHERE status=’Available’”, objcon)
dr = com.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr.Item(0))
End While
dr.Close()
objcon.Close()
Catch ex As Exception
End Try
End Sub
Sub readData()
Self-Instructional
Material 93
Lab: Visual Basic ListView1.Clear()
Programming
ListView1.Columns.Add(“BOOK ID”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“GROUP ID”, 90,
NOTES HorizontalAlignment.Center)
ListView1.Columns.Add(“BOOK NAME”, 310,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PUBLISHER”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“AUTHOR”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PUBLISHING YEAR”, 130,
HorizontalAlignment.Center)
ListView1.Columns.Add(“EDITION”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PRICE”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“STATUS”, 90,
HorizontalAlignment.Center)
ListView1.GridLines = True
ListView1.View = View.Details
Try
ListView1.Items(i).Selected = True
Exit For
End If
Self-Instructional
96 Material
Next Lab: Visual Basic
Programming
End If
Catch
NOTES
End Try
End Sub
End Try
End Sub
NOTES
Private Sub ComboBox5_SelectedIndexChanged(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles
ComboBox5.SelectedIndexChanged
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“Select CID,CName from
Customer”, objcon)
dr = com.ExecuteReader
While dr.Read
If dr.Item(0) = ComboBox5.Text Then
TextBox1.Text = dr.Item(1)
End If
End While
dr.Close()
objcon.Close()
Catch ex As Exception
End Try
End Sub
NOTES
Private Sub Button5_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button5.Click
Try
Dim i As Integer
For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).Selected = True Then
TextBox1.Text = ListView1.Items(i - 1).SubItems(0).Text
Exit For
End If
Next
ListView1.Focus()
ListView1.FullRowSelect = True
Catch ex As Exception
End Try
End Sub
End Class
Return Book:
Public Class ReturnBook
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“DELETE FROM Returns WHERE
BookID=’” & ComboBox1.Text & “‘“, objcon)
Self-Instructional
100 Material
com.ExecuteNonQuery() Lab: Visual Basic
Programming
MsgBox(“Deleted Success!”, 0, “”)
Call ClearThem()
objcon.Close()
NOTES
Catch ex As Exception
End Try
End If
End Sub
Sub ClearThem()
ComboBox1.TabIndex = “”
ComboBox2.Text = “”
TextBox2.Text = “”
TextBox3.Text = “”
TextBox6.Text = “”
ComboBox5.Text = “”
TextBox1.Text = “”
TextBox7.Text = “”
DateTimePicker2.Refresh()
End Sub
End Sub
Sub BookID_Combo()
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“Select BookID from Books
WHERE status=’Rented’”, objcon)
dr = com.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr.Item(0))
End While
dr.Close()
Self-Instructional
Material 101
Lab: Visual Basic objcon.Close()
Programming
Catch ex As Exception
End Try
NOTES
End Sub
Sub readData()
ListView1.Clear()
ListView1.Columns.Add(“BOOK ID”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“GROUP ID”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“BOOK NAME”, 310,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PUBLISHER”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“AUTHOR”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PUBLISHING YEAR”, 130,
HorizontalAlignment.Center)
ListView1.Columns.Add(“EDITION”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“PRICE”, 90,
HorizontalAlignment.Center)
ListView1.Columns.Add(“STATUS”, 90,
HorizontalAlignment.Center)
ListView1.View = View.Details
Try
Self-Instructional
102 Material
‘MsgBox(“Please Refresh”, MsgBoxStyle.Information, “”) Lab: Visual Basic
Programming
End Try
End Sub
Public Sub adddatatolistview(ByVal lvw As ListView, ByVal
NOTES
BookID As String, ByVal GroupID As String, ByVal BookName As
String, ByVal Publisher As String, ByVal Author As String,
ByVal PubYear As String, ByVal edi As String, ByVal pric As
String, ByVal st As String)
Dim lv As New ListViewItem
lvw.Items.Add(lv)
lv.Text = BookID
lv.SubItems.Add(GroupID)
lv.SubItems.Add(BookName)
lv.SubItems.Add(Publisher)
lv.SubItems.Add(Author)
lv.SubItems.Add(PubYear)
lv.SubItems.Add(edi)
lv.SubItems.Add(pric)
lv.SubItems.Add(st)
End Sub
Self-Instructional
Material 103
Lab: Visual Basic Private Sub ComboBox1_SelectedIndexChanged(ByVal sender
Programming As System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
Dim i As Integer
NOTES ListView1.SelectedItems.Clear()
TextBox1.Focus()
Try
If Me.ComboBox1.Text = “” Then
TextBox2.Text = “”
Else
For i = 0 To ListView1.Items.Count - 1
If ComboBox1.Text = ListView1.Items(i).SubItems(0).Text
Then
ComboBox2.Text = ListView1.Items(i).SubItems(1).Text
TextBox2.Text = ListView1.Items(i).SubItems(2).Text
ListView1.Items(i).Selected = True
Exit For
End If
Next
End If
Catch
End Try
Call IssueDetail()
End Sub
Sub IssueDetail() ‘
Try
If objcon.State = ConnectionState.Closed Then
objcon.Open()
com = New OleDb.OleDbCommand(“Select IssueDate, IssueName,
IssueTo, DueDate from Issue WHERE BookID=’” & ComboBox1.Text
& “‘“, objcon)
dr = com.ExecuteReader
While dr.Read
ComboBox5.Text = dr.Item(2)
TextBox1.Text = dr.Item(1)
TextBox3.Text = dr.Item(0)
TextBox7.Text = dr.Item(3)
End While
Self-Instructional
104 Material
dr.Close() Lab: Visual Basic
Programming
objcon.Close()
Catch ex As Exception
NOTES
End Try
End Sub
End Try
End Sub
Self-Instructional
Material 105
Lab: Visual Basic End Try
Programming
End Sub
End Class
NOTES
Self-Instructional
106 Material
Lab: Visual Basic
Programming
NOTES
Button Click:
Dim strSQL As String
Dim gndr As String
Dim i As Integer
If rdbFemale.Checked = True Then
gndr = “Female”
Else
gndr = “Male”
End If
strSQL = “insert into studentmaster values(“ &
txtStuID.Text & “,’” & cboClass.Text & “‘,’” & txtStuName.Text
& “‘,’” & txtFName.Text & “‘,’” & txtMName.Text & “‘,’” & gndr
& “‘,’” & txtPhone.Text & “‘,’” & txtEmail.Text & “‘)”
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
For i = 0 To dgvMarks.RowCount - 2
strSQL = “insert into studentmarks values(“ & txtStuID.Text
& “,’” & dgvMarks.Item(0, i).Value & “‘,” & dgvMarks.Item(1,
i).Value & “)”
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
Next
Search Button:
Dim sid, cnt As Integer
Dim drl As OleDb.OleDbDataReader
Dim cmdl As New OleDb.OleDbCommand
sid = CInt(InputBox(“Enter the StudentID to search”))
cmdl = New OleDbPress Ctrl+V to copy the following code
Self-Instructional
Material 107
Lab: Visual Basic
Programming
Dim sid, cnt As Integer
Dim drl As OleDb.OleDbDataReader
Dim cmdl As New OleDb.OleDbCommand
NOTES
sid = CInt(InputBox(“Enter the StudentID to search”))
cmdl = New OleDb.OleDbCommand(“select * from studentmaster
where stuid=” & sid, conDB)
drl = cmdl.ExecuteReader()
If drl.Read() Then
txtStuID.Text = drl.Item(0)
cboClass.Text = drl.Item(1)
txtStuName.Text = drl.Item(2)
txtFName.Text = drl.Item(3)
txtMName.Text = drl.Item(4)
If drl.Item(5) = “Female” Then
rdbFemale.Checked = True
Else
rdbMale.Checked = True
End If
txtPhone.Text = drl.Item(6)
txtEmail.Text = drl.Item(7)
drl.Close()
cmdl = New OleDb.OleDbCommand(“select subject, marks
from studentmarks where stuid=” & sid, conDB)
drl = cmdl.ExecuteReader()
dgvMarks.Rows.Clear()
cnt = 0
While drl.Read()
dgvMarks.Rows.Add()
dgvMarks.Item(0, cnt).Value = Convert.ToString
(drl.Item(0))
dgvMarks.Item(1, cnt).Value = Convert.ToString
(drl.Item(1))
cnt = cnt + 1
End While
Else
MsgBox(“No student with this ID”)
End If
Self-Instructional
108 Material
.OleDbCommand(“select * from studentmaster where stuid=” Lab: Visual Basic
& sid, conDB) Programming
drl = cmdl.ExecuteReader()
If drl.Read() Then
NOTES
txtStuID.Text = drl.Item(0)
cboClass.Text = drl.Item(1)
txtStuName.Text = drl.Item(2)
txtFName.Text = drl.Item(3)
txtMName.Text = drl.Item(4)
If drl.Item(5) = “Female” Then
rdbFemale.Checked = True
Else
rdbMale.Checked = True
End If
txtPhone.Text = drl.Item(6)
txtEmail.Text = drl.Item(7)
drl.Close()
cmdl = New OleDb.OleDbCommand(“select subject, marks
from studentmarks where stuid=” & sid, conDB)
drl = cmdl.ExecuteReader()
dgvMarks.Rows.Clear()
cnt = 0
While drl.Read()
dgvMarks.Rows.Add()
dgvMarks.Item(0, cnt).Value = Convert.ToString
(drl.Item(0))
dgvMarks.Item(1, cnt).Value = Convert.ToString
(drl.Item(1))
cnt = cnt + 1
End While
Else
MsgBox(“No student with this ID”)
End If
Self-Instructional
Material 109
Lab: Visual Basic Button Update:
Programming
Dim strSQL As String
Dim gndr As String
NOTES Dim i As Integer
If rdbFemale.Checked = True Then
gndr = “Female”
Else
gndr = “Male”
End If
strSQL = “update studentmaster set stuClass=’” &
cboClass.Text & “‘, StuName=’” & txtStuName.Text & “‘,
StuFname=’” _
& txtFName.Text & “‘,StuMName=’” & txtMName.Text &
“‘,StuGender=’” & gndr & “‘,StuPhone=’” & txtPhone.Text _
& “‘,StuEmail=’” & txtEmail.Text & “‘ where StuID=” &
CInt(txtStuID.Text)
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
‘ delete all records from marks table to add the new
marks and subjects
strSQL = “delete * from studentmarks where StuID=” &
CInt(txtStuID.Text)
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
‘ Insert the new subjects and marks for the student
For i = 0 To dgvMarks.RowCount - 2
strSQL = “insert into studentmarks values(“ & txtStuID.Text
& “,’” & dgvMarks.Item(0, i).Value & “‘,” & dgvMarks.Item(1,
i).Value & “)”
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
Next
Button Delete:
Dim strSQL As String
‘ delete the record of student from master table
strSQL = “delete * from studentmaster where StuID=” &
CInt(txtStuID.Text)
cmd = New OleDb.OleDbCommand(strSQL, conDB)
cmd.ExecuteNonQuery()
‘ delete all records from marks table
Self-Instructional
110 Material
strSQL = “delete * from studentmarks where StuID=” & Lab: Visual Basic
CInt(txtStuID.Text) Programming
Self-Instructional
Material 111
Lab: Visual Basic 3. Telephone Directory Maintenance
Programming
Imports System.IO
Imports System.IO.Directory
NOTES Imports System.IO.DirectoryInfo
Imports System.IO.Path
Imports System.Environment
Imports System.IO.FileStream
Imports System.IO.File
Imports System.IO.FileInfo
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.OleDb
Self-Instructional
112 Material
Select Case e.KeyCode Lab: Visual Basic
Programming
Case Keys.F8
If Me.cmdAdd.Enabled = True Then
Me.cmdAdd_Click(sender, e)
NOTES
End If
Case Keys.F9
If Me.cmdEdit.Enabled = True Then
Me.cmdEdit_Click(sender, e)
End If
Case Keys.F10
If Me.cmdDelete.Enabled = True Then
Me.cmdDelete_Click(sender, e)
End If
Case Keys.F11
If Me.cmdUpdate.Enabled = True Then
Me.cmdUpdate_Click(sender, e)
End If
Case Keys.F12
If Me.cmdCancel.Enabled = True Then
Me.cmdCancel_Click(sender, e)
End If
Case Keys.Enter
SendKeys.Send(“{TAB}”)
End Select
End Sub
Me.txtFstNam.ReadOnly = False
Me.txtLstNam.ReadOnly = False
Me.txtMidNam.ReadOnly = False
Me.txtHomAdr.ReadOnly = False
Me.txtBusAdr.ReadOnly = False
Me.txtTelNo.ReadOnly = False
Me.txtMobNo.ReadOnly = False
Me.txtEml.ReadOnly = False
End Sub
Private Sub lockField()
Me.txtFstNam.ReadOnly = True
Me.txtLstNam.ReadOnly = True
Me.txtMidNam.ReadOnly = True
Me.txtHomAdr.ReadOnly = True
Me.txtBusAdr.ReadOnly = True
Me.txtTelNo.ReadOnly = True
Me.txtMobNo.ReadOnly = True
Me.txtEml.ReadOnly = True
End Sub
Private Sub UpdtOff()
Self-Instructional
116 Material
Me.cmdAdd.Enabled = True Lab: Visual Basic
Programming
Me.cmdEdit.Enabled = True
Me.cmdDelete.Enabled = True
Me.cmdUpdate.Enabled = False
NOTES
Me.cmdCancel.Enabled = False
Me.cmdAdd.BackColor = Color.Tan
Me.cmdEdit.BackColor = Color.Tan
Me.cmdDelete.BackColor = Color.Tan
Me.cmdUpdate.BackColor = Color.Black
Me.cmdCancel.BackColor = Color.Black
End Sub
Private Sub UpdtOn()
Me.cmdAdd.Enabled = False
Me.cmdEdit.Enabled = False
Me.cmdDelete.Enabled = False
Me.cmdUpdate.Enabled = True
Me.cmdCancel.Enabled = True
Me.cmdAdd.BackColor = Color.Black
Me.cmdEdit.BackColor = Color.Black
Me.cmdDelete.BackColor = Color.Black
Me.cmdUpdate.BackColor = Color.Tan
Me.cmdCancel.BackColor = Color.Tan
End Sub
Self-Instructional
Material 117
Lab: Visual Basic Private Sub cmdEdit_Click(ByVal sender As System.Object,
Programming ByVal e As System.EventArgs) Handles cmdEdit.Click
strAction = “EDIT”
UpdtOn()
NOTES
UnlockField()
End Sub
sqlCommand.ExecuteNonQuery()
cnPhoneBook.Close()
dsContact.Clear()
daContact.Fill(dsContact, “TblContact”)
MsgBox(“Record has been deleted”, MsgBoxStyle.OkOnly +
MsgBoxStyle.Information + MsgBoxStyle.ApplicationModal, “Phone
Book”)
Catch ex As Exception
MsgBox(Err.Description)
End Try
Else
Self-Instructional
118 Material
End If Lab: Visual Basic
Programming
dsContactNam.Clear()
daContactNam.Fill(dsContactNam, “TblContact”)
cmbSearch.SelectedIndex = -1
NOTES
End Sub
Try
Select Case strAction
Case “ADD”
Me.BindingContext(dsContact, “TblContact”).
EndCurrentEdit()
cnPhoneBook.Open()
strSQL = “INSERT INTO TblContact (LastName, FirstName,
MiddleName, HomeAdr, BusAdr, TelNo, MobNo, EMail) “
strSQL = strSQL & “ VALUES (‘“ & Me.txtLstNam.Text &
“‘,’” & Me.txtFstNam.Text & “‘,’” & Me.txtMidNam.Text & “‘,’”
& Me.txtHomAdr.Text & “‘,’” & Me.txtBusAdr.Text & “‘,’” &
Me.txtTelNo.Text & “‘,’” & Me.txtMobNo.Text & “‘,’” &
Me.txtEml.Text & “‘);”
sqlCommand = New OleDbCommand(strSQL, cnPhoneBook)
sqlCommand.ExecuteNonQuery()
cnPhoneBook.Close()
dsContact.Clear()
daContact.Fill(dsContact, “TblContact”)
Case “EDIT”
intPos = Me.BindingContext(dsContact, “TblContact”).
Position
intContactID = dtContact.Rows(intPos).Item(1)
Me.BindingContext(dsContact, “TblContact”).
EndCurrentEdit()
cnPhoneBook.Open()
Self-Instructional
Material 119
Lab: Visual Basic strSQL = “UPDATE TblContact SET LastName = ‘“ &
Programming Me.txtLstNam.Text & “‘, FirstName = ‘“ & Me.txtFstNam.Text &
“‘, MiddleName = ‘“ & Me.txtMidNam.Text & “‘, HomeAdr = ‘“ &
Me.txtHomAdr.Text & “‘, “
NOTES strSQL = strSQL & “ BusAdr = ‘“ & Me.txtBusAdr.Text & “‘,
TelNo = ‘“ & Me.txtTelNo.Text & “‘, MobNo = ‘“ & Me.txtMobNo.Text
& “‘, EMail = ‘“ & Me.txtEml.Text & “‘ WHERE
(((TblContact.ContactID)=” & intContactID & “));”
sqlCommand = New OleDbCommand(strSQL, cnPhoneBook)
sqlCommand.ExecuteNonQuery()
cnPhoneBook.Close()
SubPos = Me.BindingContext(dsContact,
“TblContact”).Position
dsContact.Clear()
daContact.Fill(dsContact, “TblContact”)
Me.BindingContext(dsContact, “TblContact”).Position =
SubPos
End Select
UpdtOff()
lockField()
Catch ex As Exception
MsgBox(strSQL)
End Try
dsContactNam.Clear()
daContactNam.Fill(dsContactNam, “TblContact”)
Me.txtRecPos.Text = “Contact Record “ &
Me.BindingContext(dsContact, “TblContact”).Position + 1 & “
of : “ & dsContact.Tables(“TblContact”).Rows.Count
End Sub
Private Sub cmdCancel_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdCancel.Click
Me.BindingContext(dsContact, “TblContact”).
CancelCurrentEdit()
UpdtOff()
lockField()
Me.txtRecPos.Text = “Contact Record “ &
Me.BindingContext(dsContact, “TblContact”).Position + 1 & “
of : “ & dsContact.Tables(“TblContact”).Rows.Count
End Class
Self-Instructional
124 Material
#End If ‘ Compile_Command5_Click Lab: Visual Basic
Programming
End Sub
L2.Top -= 60
If L2.Top<=100 Then
L2.Top = 13000
End If
L3.Top -= 60
If L3.Top<=100 Then
L3.Top = 13000
End If
L4.Top -= 60
If L4.Top<=100 Then
L4.Top = 13000
End If
L5.Top -= 60
If L5.Top<=100 Then
L5.Top = 13000
End If
L6.Top -= 60
If L6.Top<=60 Then
L6.Top = 13000
End If
Self-Instructional
126 Material
l7.Top -= 60 Lab: Visual Basic
Programming
If l7.Top<=60 Then
l7.Top = 13000
End If
NOTES
l8.Top -= 60
If l8.Top<=60 Then
l8.Top = 13000
End If
l9.Top -= 60
If l9.Top<=60 Then
l9.Top = 13000
End If
#End If ‘ Compile_Timer1_Timer
End Sub
End Class
Self-Instructional
Material 127
Lab: Visual Basic
Programming
NOTES
File Menu:
Booking Menu:
Add Menu:
Customer Form:
Private Sub Cmdadd_Click()
Adodc1.Refresh
Adodc1.Recordset.AddNew
End Sub
cmbgn.Text = “”
txtnm.Text = “”
txtad.Text = “”
cmbec.Text = “”
cmbct.Text = “”
Txtpn.Text = “”
cmbpro.Text = “”
Txtdob.Text = “”
End If
End Sub
Bill:
Private Sub Cmbnm2_LostFocus()
‘On Error Resume Next
‘Adodc1.Refresh
‘While Not Adodc1.Recordset.EOF = True
‘If Adodc1.Recordset!Name = Cmbnm2.Text Then
‘txtadd.Text = Adodc1.Recordset!Add ‘ress
‘Txtex.Text = Adodc1.Recordset!Exchange
‘Txtpin.Text = Adodc1.Recordset!pincode
‘Else
‘’
‘’Exit Do
‘End If
‘Loop
Adodc1.Refresh
Self-Instructional
Material 131
Lab: Visual Basic Adodc2.Refresh
Programming
Do While Adodc1.Recordset.EOF = False
If Adodc1.Recordset!Name = Cmbnm2.Text Then
Txtadd.Text = Adodc1.Recordset!Add
NOTES
Txtex.Text = Adodc1.Recordset!Exchange
Txtpin.Text = Adodc1.Recordset!pincode
Text1.Text = Adodc1.Recordset!plan
Exit Do
End If
‘End If
Adodc1.Recordset.MoveNext
‘Adodc2.Recordset.MoveNext
Loop
‘Adodc2.Recordset.MoveNext
Txtn2.Text = Cmbnm2.Text
Txtn3.Text = Txtadd.Text
Txtn4.Text = txtcust.Text
Txtn5.Text = Txttel.Text
Txtn6.Text = Txtex.Text
Txtn7.Text = Txtpin.Text
Txtdb.Text = Txtfmc.Text
Txtdb1.Text = txtfc.Text
‘Wend
End Sub
Self-Instructional
132 Material
Private Sub Cmdadd_Click() Lab: Visual Basic
Programming
Adodc3.Refresh
Adodc3.Recordset.MoveNext
Adodc3.Recordset.AddNew
NOTES
Cmdadd.Visible = False
cmdsv.Visible = True
End Sub
cmdsv.Visible = False
‘Val(Txtgmc.Text) = Val(Txtcmr.Text) - Val(Txtomr.Text)
End Sub
Self-Instructional
136 Material
6. Bank Transaction System Lab: Visual Basic
Programming
Bank Details:
Public Class bankd
Private Sub Label2_Click(sender As Object, e As EventArgs) NOTES
End Sub
Self-Instructional
Material 137
Lab: Visual Basic Deposit:
Programming
Public Class Deposit
Private Sub cls_Click(sender As Object, e As EventArgs)
Handles cls.Click
NOTES
Me.Hide()
End Sub
End Sub
Self-Instructional
140 Material
Withdraw: Lab: Visual Basic
Programming
Public Class Withdraw
Private Sub AddAccountToolStripMenuItem_Click(sender As
Ob je c t, e A s E ven t Ar gs) Ha n d le s A dd A c co u nt Too l S
tripMenuItem.Click NOTES
End Sub
7. Payroll Processing
Login:
Imports System.Data.OleDb
Public Class frmloginA
Self-Instructional
142 Material
If (sdr.Read() = True) Then Lab: Visual Basic
Programming
MessageBox.Show(“You are Now Logged In”)
frmMainA.Show()
TextBox1.Focus()
NOTES
TextBox1.Clear()
txtPassword.Clear()
Me.Hide()
Else
MessageBox.Show(“Invalid Username or Password!”)
End If
End Sub
NOTES
Private Sub GroupBox1_Enter(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles GroupBox1.Enter
End Sub
Form Main:
Imports System.IO
Public Class frmMainA
Private Sub Timer1_Tick(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Timer1.Tick
lblTime.Text = DateTime.Now.ToString(“hh:mm:ss tt”)
lblDate.Text = DateTime.Now.ToString(“MMMM dd yyyy”)
End Sub
End Sub
NOTES
Private Sub SearchRecordsToolStripMenuItem_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
Print Slip:
Public Class frmpayslip
Private Sub GenPayFinalBindingNavigatorSaveItem_
Click(ByVal sender As System.Object, ByVal e As System.
EventArgs)
Me.Validate()
Me.GenPayFinalBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.GenerallPayrollDataSet)
End Sub
Self-Instructional
Material 147
Lab: Visual Basic Private Sub TuitionLabel_Click(ByVal sender As
Programming
System.Object, ByVal e As System.EventArgs)
End Sub
NOTES
Private Sub Button5_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button5.Click
Me.Validate()
Me.GenPayFinalBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.GenerallPayrollDataSet)
MessageBox.Show(“Successfully Added”)
End Sub
Catch ex As Exception
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.
Self-Instructional
148 Material
OK, MessageBoxIcon.Error) Lab: Visual Basic
Programming
End Try
End Sub
NOTES
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
txtReceipt.Text = “”
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab + vbTab + vbTab +
vbTab + vbTab & “PAY-SLIP” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“Plantilla Number: “ + vbTab &
PlantIDTextBox.Text + vbTab + vbTab + vbTab + vbNewLine)
txtReceipt.AppendText(“Employee Name: “ + vbTab &
EmployeeNameTextBox.Text + vbTab + vbTab + vbNewLine)
txtReceipt.AppendText(“Number: “ + vbTab + vbTab &
NoTextBox.Text + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“Basic Salary: “ + vbTab &
BasicTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Pera: “ + vbTab + vbTab &
PERATextBox.Text + vbNewLine)
txtReceipt.AppendText(“Gross Amount: “ + vbTab &
GrossAmountTextBox.Text + vbNewLine)
txtReceipt.AppendText(“= = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = “ + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab & “Deductions” +
Self-Instructional
Material 149
Lab: Visual Basic vbNewLine)
Programming
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“W/ Tax: “ + vbTab + vbTab + vbTab
& WtaxTextBox.Text + vbNewLine)
NOTES
txtReceipt.AppendText(“GSIS Premium: “ + vbTab + vbTab
& GSISPremiumTextBox.Text + vbNewLine)
txtReceipt.AppendText(“GSIS Salary Loan: “ + vbTab &
GSISSalaryLoanTextBox.Text + vbNewLine)
txtReceipt.AppendText(“GSIS EL: “ + vbTab + vbTab &
GSISELTextBox.Text + vbNewLine)
txtReceipt.AppendText(“GSIS EMRGL: “ + vbTab + vbTab &
GSISEMRGLTextBox.Text + vbNewLine)
txtReceipt.AppendText(“GSIS PL: “ + vbTab + vbTab &
GSISPLTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Pag-Ibig Premium: “ + vbTab &
PagIbigPremTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Pag-Ibig ML: “ + vbTab + vbTab &
PagIbigMLTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Pag-Ibig 2: “ + vbTab + vbTab &
PagIbig2TextBox.Text + vbNewLine)
txtReceipt.AppendText(“Phil Health Premium: “ + vbTab &
PhilHealthPremiunTextBox.Text + vbNewLine)
txtReceipt.AppendText(“LEAP: “ + vbTab + vbTab + vbTab
& LEAPTextBox.Text + vbNewLine)
txtReceipt.AppendText(“IGP: “ + vbTab + vbTab + vbTab &
IGPTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Faculty Union: “ + vbTab + vbTab
& FacultyUnionTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Refund Disallow: “ + vbTab &
RefundDisallowTextBox.Text + vbNewLine)
txtReceipt.AppendText(“Tuition: “ + vbTab + vbTab +
vbTab & TuitionTextBox.Text + vbNewLine)
txtReceipt.AppendText(“LBP Payment: “ + vbTab + vbTab &
LBPPaymentTextBox.Text + vbNewLine)
txtReceipt.AppendText(“City Savings: “ + vbTab + vbTab
& CitySavingsTextBox.Text + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“Total Deductions: “ + vbTab &
TotalDeductionTextBox.Text + vbTab + vbTab & “NET Amount: “ +
vbTab & NETAmountTextBox.Text + vbNewLine)
Self-Instructional
150 Material
txtReceipt.AppendText(“= = = = = = = = = = = = = = = = Lab: Visual Basic
Programming
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = “ + vbNewLine)
txtReceipt.AppendText(vbTab & “Due Date: “ + Today &
vbTab + vbTab + vbTab + vbTab + vbTab + vbTab & “Time: “ & NOTES
TimeOfDay + vbNewLine)
txtReceipt.AppendText(“= = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = “ + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(vbTab + “Recieve by:” + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab + vbTab +
“___________________” + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab + vbTab +
EmployeeNameTextBox.Text + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab + vbTab + “ Employee”
+ vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“” + vbNewLine)
txtReceipt.AppendText(“= = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = “ + vbNewLine)
txtReceipt.AppendText(“ Need Help? Contact Us: 09096510899
“ + vbNewLine)
txtReceipt.AppendText(“= = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = “ + vbNewLine)
txtReceipt.AppendText(vbTab + vbTab + vbTab +
PictureBox1.Text + vbNewLine)
PrintPreviewDialog1.ShowDialog()
End Sub
Self-Instructional
Material 151
Lab: Visual Basic e.Graph ics.Dr awStri ng(tx tRe ceipt.Tex t, Font,
Programming
Brushes.Black, 140, 140)
e.Graphics.DrawImage(Me.PictureBox1.Image, 120, 130,
PictureBox1.Width - 15, PictureBox1.Height - 25)
NOTES
e.Graphics.DrawImage(Me.PictureBox2.Image, 300, 130,
PictureBox2.Width - 15, PictureBox2.Height - 25)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
TotalDeductionTextBox.Text = Val(WtaxTextBox.Text) +
Val(GSISPremiumTextBox.Text) + Val(GSISSalaryLoanTextBox.Text)
+ Val(GSISELTextBox.Text) + Val(GSISEMRGLTextBox.Text) +
Val(GSISPLTextBox.Text) + Val(PagIbigPremTextBox.Text) +
Val(PagIbigMLTextBox.Text) + Val(PagIbig2TextBox.Text) +
Val(PhilHealthPremiunTextBox.Text) + Val(LEAPTextBox.Text) +
Val(IGPTextBox.Text) + Val(FacultyUnionTextBox.Text) +
Val(RefundDisallowTextBox.Text) + Val(TuitionTextBox.Text) +
Val(LBPPaymentTextBox.Text) + Val(CitySavingsTextBox.Text)
GrossAmountTextBox.Text = Val(BasicTextBox.Text) +
Val(PERATextBox.Text)
NETAmountTextBox.Text = Val(GrossAmountTextBox.Text) -
Val(TotalDeductionTextBox.Text)
NETAmountTextBox.Text = FormatCurrency(NETAmountTextBox.
Text)
TotalDeductionTextBox.Text = FormatCurrency(Total
DeductionTextBox.Text)
GrossAmountTextBox.Text = FormatCurrency(Gross
AmountTextBox.Text)
MessageBox.Show(“Successfully Computed”)
End Sub
Self-Instructional
152 Material
Private Sub Button8_Click(ByVal sender As System.Object, Lab: Visual Basic
Programming
ByVal e As System.EventArgs) Handles Button8.Click
GenPayFinalBindingSource.MovePrevious()
End Sub
NOTES
Self-Instructional
Material 153
Lab: Visual Basic Call openconnection()
Programming
Call Initialized()
Call LoadListView()
Call closeconnection()
NOTES
End Sub
Public Sub LoadListView()
lststudent.Items.Clear()
Call Initialized()
Oledr = OleDa.SelectCommand.ExecuteReader()
Do While Oledr.Read()
Item = lststudent.Items.Add(Oledr(“studentno”).ToString())
Item.SubItems.Add(Oledr(“firstname”).ToString())
Item.SubItems.Add(Oledr(“lastname”).ToString())
Item.SubItems.Add(Oledr(“course”).ToString())
Loop
Oledr.Close()
End Sub
Self-Instructional
154 Material
If lststudent.SelectedItems.Count = 0 Then Lab: Visual Basic
Programming
MsgBox(“Please choose the record you want to edit”,
MsgBoxStyle.Information)
Return True
NOTES
Exit Function
End If
End Function
Self-Instructional
Material 155
Lab: Visual Basic MsgBox(“Delete Cancelled.”, MsgBoxStyle.Information)
Programming
lststudent.SelectedItems.Clear()
Exit Sub
End If
NOTES
For Each Item As ListViewItem In lststudent.SelectedItems
Item.Remove()
OleDa.DeleteCommand = New OleDbCommand()
Call openconnection()
OleDa.DeleteCommand.CommandText = “DELETE FROM tblstudent
WHERE studentno = @studentno”
OleDa.DeleteCommand.Connection = OleCn
OleDa.DeleteCommand.Parameters.Add(“@studentno”,
OleDbType.VarChar, 50, “studentno”).Value =
Item.Text.ToString()
OleDa.DeleteCommand.ExecuteNonQuery()
Call LoadListView()
Call closeconnection()
Next
MsgBox(“Record Deleted”)
lststudent.SelectedItems.Clear()
End Sub
Self-Instructional
156 Material
OleDa.SelectCommand.Connection = OleCn Lab: Visual Basic
Programming
Oledr = OleDa.SelectCommand.ExecuteReader()
Do While Oledr.Read()
ItemSearch = lststudent.Items.Add(Oledr(“studentno”).
NOTES
ToString())
ItemSearch.SubItems.Add(Oledr(“firstname”).ToString())
ItemSearch.SubItems.Add(Oledr(“lastname”).ToString())
ItemSearch.SubItems.Add(Oledr(“course”).ToString())
Loop
Oledr.Close()
End Sub
Self-Instructional
Material 157
Lab: Visual Basic Add Information:
Programming
Imports System.Data.OleDb
Public Class frmadd
NOTES Private Sub frmadd_FormClosing(ByVal sender As Object,
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles
Me.FormClosing
Call cleartext()
txtsn.Focus()
frmmain.lststudent.SelectedItems.Clear()
End Sub
Self-Instructional
158 Material
Call openconnection() Lab: Visual Basic
Programming
OleDa.InsertCommand = New OleDbCommand()
OleDa.InsertCommand.CommandText = “INSERT INTO tblstudent
(studentno, firstname, lastname, course)” & _
NOTES
“VALUES (@studentno , @firstname, @lastname, @course)”
OleDa.InsertCommand.Connection = OleCn
OleDa.InsertCommand.Parameters.Add(“@studentno”,
OleDbType.VarWChar, 50, “studentno”).Value = txtsn.Text
OleDa.InsertCommand.Parameters.Add(“@firstname”,
OleDbType.VarWChar, 50, “firstname”).Value = txtfn.Text
OleDa.InsertCommand.Parameters.Add(“@lastname”,
OleDbType.VarWChar, 50, “lastname”).Value = txtln.Text
OleDa.InsertCommand.Parameters.Add(“@course”,
OleDbType.VarWChar, 50, “course”).Value = cmbcourse.Text
OleDa.InsertCommand.ExecuteNonQuery()
Call frmmain.LoadListView()
Call closeconnection()
MsgBox(“Records Saved”, MsgBoxStyle.Information, “Saved”)
Me.Close()
Catch ex As Exception
MsgBox(“Cannot Save this record, Existing Student Number”,
MsgBoxStyle.Information, “Error”)
Call closeconnection()
txtsn.Focus()
txtsn.SelectAll()
End Try
End Sub
End Class
Delete Record:
Self-Instructional
Material 159
Lab: Visual Basic Edit Record:
Programming
Imports System.Data.OleDb
Public Class frmedit
NOTES Private Sub frmedit_FormClosing(ByVal sender As Object,
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles
Me.FormClosing
Call cleartext()
txtsn.Focus()
frmmain.lststudent.SelectedItems.Clear()
End Sub
Self-Instructional
160 Material
If OleDr.HasRows() Then Lab: Visual Basic
Programming
OleDr.Read()
txtsn.Text = OleDr(“studentno”).ToString()
txtfn.Text = OleDr(“firstname”).ToString() NOTES
txtln.Text = OleDr(“lastname”).ToString()
cmbcourse.Text = OleDr(“course”).ToString()
End If
OleDr.Close()
End Sub
Self-Instructional
Material 161
Lab: Visual Basic OleDa.UpdateCommand.Parameters.Add(“@Course”,
Programming
OleDbType.VarWChar, 50, “Course”).Value = cmbcourse.Text
OleDa.UpdateCommand.Parameters.Add(New
System.Data.OleDb.OleDbParameter(“EmpID”,
NOTES System.Data.OleDb.OleDbType.VarWChar, 50, _
System.Data.ParameterDirection.Input, False, CType(0,
Byte), CType(0, Byte), “studentno”, _
System.Data.DataRowVersion.Original, Nothing)).Value =
frmmain.lststudent.SelectedItems(0).Text
OleDa.UpdateCommand.ExecuteNonQuery()
Call frmmain.LoadListView()
Call closeconnection()
MsgBox(“Records Updated”)
Me.Close()
Catch ex As Exception
MsgBox(“Cannot Update StudentNo is present”)
Call closeconnection()
txtsn.Focus()
txtsn.SelectAll()
End Try
End Sub
End Class
Self-Instructional
162 Material
Private Sub Form2_Load(sender As Object, e As EventArgs) Lab: Visual Basic
Programming
Handles MyBase.Load
End Sub
NOTES
Private Sub LinkLabel1_LinkClicked(sender As Object, e
As LinkLabelLinkClickedEventArgs)
SIGN_IN.Show()
Me.Close()
End Sub
Self-Instructional
Material 163
Lab: Visual Basic Me.Close()
Programming
End Sub
If CheckBox1.Checked Then
password1.UseSystemPasswordChar = False
Else
password1.UseSystemPasswordChar = True
End If
End Sub
End Class
Self-Instructional
164 Material
Sign In: Lab: Visual Basic
Programming
Public Class SIGN_IN
Private Sub Button1_Click(sender As Object, e As
EventArgs) Handles Button1.Click NOTES
If username2.Text = My.Settings.Username And
password2.Text = My.Settings.Password = True Then
Home.Show()
Me.Close()
Else
MsgBox(“Incorrect Username Or Password”)
username2.Clear()
password2.Clear()
End If
End Sub
Self-Instructional
Material 165
Lab: Visual Basic password2.UseSystemPasswordChar = True
Programming
End If
End Sub
NOTES End Class
Question:
Public Class quest2
Private Sub Button2_Click(sender As Object, e As
EventArgs) Handles Button2.Click
Button2.Invalidate()
If RadioButton3.Checked Then
MsgBox(“You are correct”)
quest8.LBLRIGHT.Text = quest8.LBLRIGHT.Text + 1
Else
MsgBox(“You are wrong”)
quest8.LBLWRONG.Text = quest8.LBLWRONG.Text + 1
End If
Dim quest6 As New quest2
Dim quest2 As New quest4
quest4.Show()
Me.Hide()
End Sub
Self-Instructional
166 Material
Private Sub RadioButton4_CheckedChanged(sender As Object, Lab: Visual Basic
Programming
e As EventArgs) Handles RadioButton4.CheckedChanged
End Sub
NOTES
Private Sub RadioButton3_CheckedChanged(sender As Object,
e As EventArgs) Handles RadioButton3.CheckedChanged
End Sub
End Class
Self-Instructional
Material 167
Lab: Visual Basic Module Module1
Programming
Sub Main(ByVal args As String())
Dim objDiary As clsDiary = New clsDiary()
NOTES Dim cSelection As Char = “0”c
While cSelection <> “4”c
objDiary.Welcome()
Console.WriteLine()
Console.WriteLine(“MAIN MENU”)
Console.WriteLine(“1 – ADD RECORD”)
Console.WriteLine(“2 – VIEW RECORD”)
Console.WriteLine(“3 – EDIT RECORD”)
Console.WriteLine(“4 – DELETE RECORD”)
Console.WriteLine(“5 – EDIT PASSWORD”)
Console.WriteLine(“6 – EXIT”)
Console.WriteLine(“ENTER YOUR CHOICE”)
cSelection = Console.ReadKey().KeyChar
Console.WriteLine()
Select Case cSelection
Case “1”c
objDiary.Add()
Case “2”c
objDiary.View()
Case “3”c
objDiary.Edit()
Case “4”c
objDiary.Delete()
Case “5”c
objDiary.Edit()
Case “6”c
Console.WriteLine(“Press any key to exit.”)
Case Else
Console.WriteLine(“Error.”)
Self-Instructional
168 Material
End Select Lab: Visual Basic
Programming
Console.ReadKey()
End While
End Sub NOTES
End Module
Self-Instructional
Material 169
Lab: Visual Basic Next
Programming
Return lstResults
End Function
NOTES
Class clsDiary
Private dbData As clsDatabase
Public Sub New()
dbData = New clsDatabase()
End Sub
Self-Instructional
170 Material
Public Sub Search() Lab: Visual Basic
Programming
Dim dtDate As DateTime = GetDate()
Dim lstResults As List(Of clsEntry) = dbData.Find(dtDate,
_ False)
NOTES
If lstResults.Count() > 0 Then
Console.WriteLine(“Found:”)
For Each Entry As clsEntry In lstResults
Console.WriteLine(Entry)
Next
Else
Console.WriteLine(“Nothing found.”)
End If
End Sub
Self-Instructional
Material 171
Lab: Visual Basic
Programming
NOTES
Self-Instructional
172 Material