Basic Computer Coding: Visual Basic

Citation preview

BASIC COMPUTER CODING: VISUAL BASIC

BIBLIOTEX Digital Library

www.bibliotex.com

BASIC COMPUTER CODING: VISUAL BASIC

BIBLIOTEX Digital Library

www.bibliotex.com email: [email protected]

e-book Edition 2019 ISBN: 978-1-98462-690-5 (e-book)

This book contains information obtained from highly regarded resources. Reprinted material sources are indicated. Copyright for individual articles remains with the authors as indicated and published under Creative Commons License. A Wide variety of references are listed. Reasonable efforts have been made to publish reliable data and views articulated in the chapters are those of the individual contributors, and not necessarily those of the editors or publishers. Editors or publishers are not responsible for the accuracy of the information in the published chapters or consequences of their use. The publisher assumes no responsibility for any damage or grievance to the persons or property arising out of the use of any materials, instructions, methods or thoughts in the book. The editors and the publisher have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission has not been obtained. If any copyright holder has not been acknowledged, please write to us so we may rectify.

Notice: Registered trademark of products or corporate names are used only for explanation and identification without intent of infringement.

© 2019 3G E-learning LLC

In Collaboration with 3G E-Learning LLC. Originally Published in printed book format by 3G E-Learning LLC with ISBN 978-1-98462-290-7

EDITORIAL BOARD Aleksandar Mratinković is born on May 5, 1988. in Arandjelovac, Serbia. He has graduated on Economic high school (2007), The College of Tourism in Belgrade (2013), and also has a master degree of Psychology (Faculty of Philosophy, University of Novi Sad). He has been engaged in different fields of psychology (Developmental Psychology, Clinical Psychology, Educational Psychology and Industrial Psychology) and has published several scientific works.

Dan Piestun (PhD) is currently a startup entrepreneur in Israel working on the interface of Agriculture and Biomedical Sciences and was formerly presidentCEO of the National Institute of Agricultural Research (INIA) in Uruguay. Dan is a widely published scientist who has received many honours during his career including being a two-time recipient of the Amit Golda Meir Prize from the Hebrew University of Jerusalem, his areas of expertise includes stem cell molecular biology, plant and animal genetics and bioinformatics. Dan’s passion for applied science and technological solutions did not stop him from pursuing a deep connection to the farmer, his family and nature. Among some of his interest and practices counts enjoying working as a beekeeper and onboard fishing. Felecia Killings is the Founder and CEO of LiyahAmore Publishing, a publishing company committed to providing technical and educational services and products to Christian Authors. She operates as the Senior Editor and Writer, the Senior Writing Coach, the Content Marketing Specialist, Editor-in-Chief to the company’s quarterly magazine, the Executive and Host of an international virtual network, and the Executive Director of the company’s online school for Authors. She is a former high-school English instructor and professional development professor. She possesses a Master of Arts degree in Education and a Bachelor’s degree in English and African American studies. Dr. Sandra El Hajj, Ph.D. in Health Sciences from Nova Southeastern University, Florida, USA is a health professional specialized in Preventive and Global Health. With her 12 years of education obtained from one of the most prominent universities in Beirut, in addition to two leading universities in the State of Florida (USA), Dr. Sandra made sure to incorporate interdisciplinary and multicultural approaches in her work. Her long years of studies helped her create her own miniature world of knowledge linking together the healthcare field with Medical Research, Statistics, Food Technology, Environmental & Occupational Health, Preventive Health and most noteworthy her precious last degree of Global Health. Till today, she is the first and only doctor specialized in Global Health in the Middle East area. Hazem Shawky Fouda has a PhD. in Agriculture Sciences, obtained his PhD. From the Faculty of Agriculture, Alexandria University in 2008, He is working in Cotton Arbitration & Testing General Organization (CATGO).

Fozia Parveen has a Dphil in Sustainable Water Engineering from the University of Oxford. Prior to this she has received MS in Environmental Sciences from National University of Science and Technology (NUST), Islamabad Pakistan and BS in Environmental Sciences from Fatima Jinnah Women University (FJWU), Rawalpindi.

Igor Krunic 2003-2007 in the School of Economics. After graduating in 2007, he went on to study at The College of Tourism, at the University of Belgrade where he got his bachelor degree in 2010. He was active as a third-year student representative in the student parliament.Then he went on the Faculty of science, at the University of Novi Sad where he successfully defended his master’s thesis in 2013. The crown of his study was the work titled Opportunities for development of cultural tourism in Cacak“. Later on, he became part of a multinational company where he got promoted to a deputy director of logistic. Nowadays he is a consultant and writer of academic subjects in the field of tourism. Dr. Jovan Pehcevski obtained his PhD in Computer Science from RMIT University in Melbourne, Australia in 2007. His research interests include big data, business intelligence and predictive analytics, data and information science, information retrieval, XML, web services and service-oriented architectures, and relational and NoSQL database systems. He has published over 30 journal and conference papers and he also serves as a journal and conference reviewer. He is currently working as a Dean and Associate Professor at European University in Skopje, Macedonia.

Dr. Tanjina Nur finished her PhD in Civil and Environmental Engineering in 2014 from University of Technology Sydney (UTS). Now she is working as Post-Doctoral Researcher in the Centre for Technology in Water and Wastewater (CTWW) and published about eight International journal papers with 80 citations. Her research interest is wastewater treatment technology using adsorption process.

Stephen obtained his PhD from the University of North Carolina at Charlotte in 2013 where his graduate research focused on cancer immunology and the tumor microenvironment. He received postdoctoral training in regenerative and translational medicine, specifically gastrointestinal tissue engineering, at the Wake Forest Institute of Regenerative Medicine. Currently, Stephen is an instructor for anatomy and physiology and biology at Forsyth Technical Community College.

Michelle holds a Masters of Business Administration from the University of Phoenix, with a concentration in Human Resources Management. She is a professional author and has had numerous articles published in the Henry County Times and has written and revised several employee handbooks for various YMCA organizations throughout the United States.

Table of Contents Preface

Chapter 1

Introduction to Visual Basic

xi

1

Learning Objectives ............................................................................. 1 Introduction.......................................................................................... 2 1.1 Meaning of Visual Basic ............................................................... 2 1.1.1 History of Visual Basic ........................................................3 1.1.2 The Importance of Visual Basic Programming Language ..........................................................................4 1.1.3 Advantages and Disadvantages of Visual Basic ..............6 1.2 Visual Basic Environment ............................................................ 7 1.3 Building VB Applications ............................................................. 9 1.3.1 Creating Your First Application .........................................9 1.3.2 Steps in Building a Visual Basic Application .................13 1.3.3 Structure of a Visual Basic Application ...........................15 1.3.4 Drawing the User Interface and Setting Properties.......16 1.3.5 Saving Projects ....................................................................20 Summary............................................................................................. 24 Knowledge Check ............................................................................. 25 Review Questions .............................................................................. 26 References ........................................................................................... 27

Chapter 2

Data Types, Constants and Variables

29

Learning Objectives ........................................................................... 29 Introduction........................................................................................ 30 2.1 Data Types .................................................................................... 31 2.1.1 Memory Consumption ......................................................33 2.1.2 Composite Data Types .......................................................33 2.1.3 Boolean Data Type .............................................................34 2.1.4 Byte Data Type ....................................................................35 2.1.5 Char Data Type ..................................................................37 2.1.6 Decimal Data Type .............................................................39 2.1.7 Double Data Type...............................................................41

2.1.8 Integer data type.................................................................42 2.2 Variables In Visual Basic ............................................................. 44 2.2.1 Declaring Variables ...........................................................45 2.2.2 Comparing Implicit and Explicit Variable Performance ...................................................................45 2.2.3 Providing Names for the Variables..................................46 2.2.4 Static Variables ....................................................................47 2.2.5 Forcing Explicit Declaration .............................................50 2.2.6 Using a Naming Convention ............................................51 2.2.7 Understanding Variable Scope and Lifetime .................51 2.3 Constants in Visual Basic............................................................ 53 2.3.1 User-Defined Constants ...................................................54 2.3.2 Declare a Constant .............................................................55 2.3.3 Constant and Literal Data Types .....................................57 Case Study .......................................................................................... 60 Summary............................................................................................. 64 Knowledge Check ............................................................................. 66 Review Questions .............................................................................. 67 References ........................................................................................... 68

Chapter 3

Control Statements and Tools

69

Learning Objectives ........................................................................... 69 Introduction........................................................................................ 70 3.1 Statement ...................................................................................... 70 3.1.1 Declaration Statements ......................................................70 3.1.2 Executable Statements .......................................................73 3.2 Decision Making Structures ....................................................... 74 3.2.1 If...Then Statement .............................................................76 3.2.2 If...Then...Else Statement ...................................................77 3.2.3 The If...Else If...Else Statement..........................................79 3.2.4 Nested If Statements ..........................................................81 3.2.5 Select Case Statement ........................................................82 3.2.6 Nested Select Case Statement ...........................................84 3.3 Visual Basic Control .................................................................... 85 3.3.1 Control Properties ..............................................................86 3.3.2 Control Methods.................................................................86 3.3.3 Control Events ....................................................................87

3.4. Visual Basic Control Tools ......................................................... 88 3.4.1 Intrinsic Controls ................................................................88 3.4.2 ActiveX Controls.................................................................89 3.4.3 Insertable Objects ...............................................................89 Role Model.......................................................................................... 90 Summary............................................................................................. 94 Knowledge Check ............................................................................. 96 Review Questions .............................................................................. 97 References ........................................................................................... 98

Chapter 4

Menu Bar and Dialog Boxes

99

Learning Objectives ........................................................................... 99 4.1 Menu Bar..................................................................................... 100 4.1.1 Adding Menu Bar Using Visual Basic’s Application Wizard ..........................................................................100 4.1.2 Adding Menu Bar Using Menu Editor..........................106 4.2 Dialog Boxes ............................................................................... 109 4.2.1 Using a Parent Control ....................................................111 4.2.2 Dialog Box Creation .........................................................112 4.2.3 Characteristics of Dialog Boxes ......................................113 4.2.4 Modal and Modeless Dialog Boxes ...............................119 Summary .......................................................................................... 123 Knowledge Check ........................................................................... 124 Review Questions ............................................................................ 125 References ......................................................................................... 126

Chapter 5

Executing the Debugging

127

Learning Objectives ......................................................................... 127 Introduction...................................................................................... 128 5.1 Error Types ................................................................................. 128 5.1.1 Syntax Errors .....................................................................128 5.1.2 Run-time Errors ................................................................129 5.1.3 Logic Errors .......................................................................130 5.2 Debugging Visual Basic Programs .......................................... 130 5.3 Debugging Tools ........................................................................ 133 5.4 Error Handling........................................................................... 139 5.4.1 In Case Of Error, Jump To Label ....................................142 5.4.2 In Case Of Error, Jump To Line # ...................................145

5.4.3 Resume ..............................................................................146 Summary........................................................................................... 151 Knowledge Check ........................................................................... 152 Review Questions ............................................................................ 153 References ......................................................................................... 154

Chapter 6

Procedures and Arrays

155

Learning Objectives ......................................................................... 155 Introduction...................................................................................... 156 6.1 Basics of Procedures .................................................................. 156 6.1.1 Sub Procedures .................................................................157 6.1.2 Event Procedures..............................................................161 6.1.3 General Procedures ..........................................................161 6.1.4 Function Procedures ........................................................163 6.1.5 Property Procedures ........................................................166 6.2 Arrays in Visual Basic ............................................................... 171 6.2.1 Dimension of an Array ....................................................173 6.2.2 Dynamic Array .................................................................177 6.2.3 Retrieving the Contents of an Array..............................181 6.2.4 Multidimensional Arrays ................................................182 Summary........................................................................................... 186 Knowledge Check ........................................................................... 188 Review Questions ............................................................................ 189 References ......................................................................................... 190

Chapter 7

Data Access

191

Learning Objectives ......................................................................... 191 Introduction...................................................................................... 192 7.1 ADO.Net Object Model ............................................................ 192 7.1.1 Data Provider ....................................................................193 7.1.2 DataSet ...............................................................................194 7.2 Connecting to a Database ......................................................... 196 7.3 Creating Table, Columns and Rows ....................................... 205 7.4 Selecting the Data Source ......................................................... 208 7.4.1 Linking Data Sources to an Application .......................209 7.4.2 Adding SQL Statements to a Visual Basic Application...................................................................211

Role Model........................................................................................ 213 Summary........................................................................................... 216 Knowledge Check ........................................................................... 217 Review Questions ............................................................................ 218 References ......................................................................................... 219

Index

221

Preface Visual Basic is one of the most widely used programming languages in the world. The major reason for its popularity is that it allows programmers to create Windows applications quickly and easily. It was indeed the first visual development tool from Microsoft. Visual Basic was derived from BASIC and enables rapid application development of graphical user interface applications, access to databases using DAO, RDO, or ADO, and creation of ActiveX controls and objects. One of the most important things to be considered with regard to programming in Visual basic is that the structure of VB is designed in a way that allows programmers to create executable code – Exe files. It enables programmers to develop programs that can be used as front end to databases. Besides, it’s with the help of visual basic tools; one can change the abstract ideas into programs or into the whole software while it allows revising and modifying the programs fittingly. Organization of the Book This book is systematically divided into seven chapters. This book focuses on using the latest and most powerful tools from the Microsoft arsenal within your Visual Basic solutions. The book introduces the Visual Basic Integrated Development Environment (IDE) and its wealth of development tools. Students will learn to build effective user interfaces with Visual Basic controls, forms, and other GUI components. Students will learn the use of the debugging and testing tools available in Visual Studio. Database access is introduced, using Visual Basic’s ADO Control and dataaware components like the Data Grid and Data Environment Designer. Chapter 1 presents an introduction to Visual Basic. It focuses on meaning of visual basic, visual basic environment, building VB applications. Chapter 2 focuses on data types, constants and variables. The data

type defines which operations can safely be performed to create, transform and use the variable in another computation. Useful variables and constants in visual basic are also explained. Chapter 3 discusses the control statement and tools necessary to control the sequence of operations in a program. This can be done by using control statements. An executable statement performs an action. Statements calling a procedure, branching to another place in the code, looping through several statements, or evaluating an expression are executable statements. Chapter 4 focuses on menu bar and dialog boxes. It allows you to create a robust program. In general, error handling should be part of your overall program plan, so that when you have an error-free script, nothing is going to bring it to a screeching halt. Chapter 5 focuses on debugging visual basic programs, debugging tools, and error handling. Errors, bugs, and therefore debugging are a part of life for a programmer. Chapter 6 is intended to focus on the basics of procedures. The chapter also focuses on the concept of arrays in visual basic. The fundamental role of a procedure is to offer a single point of reference for some small goal or task that the developer or programmer can trigger by invoking the procedure itself. Chapter 7 focuses on Data Access feature of Visual Basic that allows you to access and manipulate any database from Visual Basic.

CHAPTER 1

INTRODUCTION TO VISUAL BASIC “I know blind programmers who work in C and Visual Basic in addition to mainframe languages, because as long as they can get at a text file, they can do programming. But if the graphical tool kit you are using requires you to drag and drop items on the screen, you can’t do it.” ―Curtis Chong,

Learning Objectives After studying this chapter, you will be able to: ■

Overview of meaning of visual basic



Discuss the visual basic environment



Describe the building VB applications

Basic Computer Coding: Visual Basic

INTRODUCTION Visual Basic is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners’ Allpurpose Symbolic Instruction Code. It is a fairly easy programming language to learn. The codes look a bit like English Language.

VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In VISUAL BASIC, programming is done in a graphical environment. Because users may click on a certain object randomly, so each object has to be programmed indepently to be able to response to those actions (events).Therefore, a VISUAL BASIC Program is made up of many subprograms, each has its own program codes, and each can be excecuted indepently and at The graphical user the same time each can be linked together in interface (GUI), is a one way or another.

type of user interface that allows users to interact with electronic devices through graphical icons and visual indicators such as secondary notation, instead of text-based user interfaces, typed command labels or text navigation.

1.1 MEANING OF VISUAL BASIC Visual Basic is a programming language and development environment created by Microsoft. It is an extension of the BASIC programming language that combines BASIC functions and commands with visual controls. Visual Basic 2

Introduction to Visual Basic

provides a graphical user interface GUI that allows the developer to drag and drop objects into the program as well as manually write program code. Visual Basic, also referred to as “VB,” is designed to make software development easy and efficient, while still being powerful enough to create advanced programs. For example, the Visual Basic language is designed to be “human readable,” which means the source code can be understood without requiring lots of comments. The Visual Basic program also includes features like “IntelliSense” and “Code Snippets,” which automatically generate code for visual objects added by the programmer. Another feature, called “AutoCorrect,” can debug the code while the program is running. Programs created with Visual Basic can be designed to run on Windows, on the Web, within Office applications, or on mobile devices. Visual Studio, the most comprehensive VB development environment, or IDE, can be used to create programs for all these mediums. Visual Studio .NET provides development tools to create programs based on the .NET framework, such as ASP.NET applications, which are often deployed on the Web.

1.1.1 History of Visual Basic The first version of visual basic, VB 1.0, was announced in the year 1991. The creation of user interface through a drag and drop design was inspired a beta generator that was developed by Alan Cooper at Tripod, which was Cooper’s company. Microsoft entered into a contract with Cooper and his partners to create Tripod into a system 3

Remember Visual Basic is available as a streamlined application that is used primarily by beginning developers and for educational purposes.

Basic Computer Coding: Visual Basic

that is programmable for Windows 3.0. This system was developed under the code name of Ruby, which has no relationship with the Ruby Programming Language. Tripod did not have any programming language at all. Microsoft then decided to use Ruby in combination with basic language to develop visual basic. The interface of Ruby contributed the “visual” component of the Visual Basic programming language. This was then amalgamated with the Embedded BASIC engine that was developed for the ceased “Omega” database system of Microsoft. The introduction of version 5.0, in the month of February in 1997, Microsoft exclusively released a visual basic that was compatible with 32-bit Microsoft Windows versions. The programmers who had a preference for writing programs in 16-bit could do it in versions between 4.0 and 5.0. In addition to that the programs written Visual Basic 5.0 can be converted to Version 4.0 programs in an easy manner. The version 5.0 also has the ability of compilation with native execution code of Windows, and introduction of custom user controls. The introduction of Visual Basic 6.0 was made in the middle of 1998. This version also came with a number of enhancements, including the striking ability of creating web based applications. The extended support for Visual Basic 6.0 was ceased in the month of March in 2008. The basic parts of development environment of Visual Basic 6, however, still run in all the 32-bit Microsoft windows, including Windows 8.1. After the cessation of mainstream and extended support for Visual Basic 6.0 caused a number of programs to show concern. The community members then created a lobby of users and a petition was signed by them. The basic aim of this petition was to ensure that the product remains alive. However, the petition did not attain its aim effectively.

1.1.2 The Importance of Visual Basic Programming Language Visual Basic is regarded as the third generation event-driven programming language. It was released in 1987. Being the first 4

Introduction to Visual Basic

visual development tool from Microsoft, it is considered as one of the most powerful programming languages. As compared to other computer programming languages, such as, C, C++, it is easy to learn and understand, provided that one has determination and dedication to do so. Visual basic programming language allows programmers to create software interface and codes in an easy to use graphical environment. VB is the combination of different components that are used on forms having specific attributes and actions with the help of those components. On the one hand it allows programmers to develop widows based applications rapidly; on the other hand, it helps greatly in accessing data bases, using ADO while letting the programmers use ActiveX controls and various objects. While it is intended more to develop applications, it is also useful for games development for particular or limited purposes, unlike C++ that is more suitable for developing games. As compared to other languages, Visual basic may be slower though, yet it is flexible and it can be rightly said that things that are difficult in other languages are comparatively easier in visual basic programming language. It may also be said that, since it is one of the most popular programming languages, lots of related books and material and other resources are available and can be accessed for developing programming skills at visual basic programming language conveniently. One of the most important things to be considered with regard to programming in Visual basic is that the structure of VB is designed in a way that allows programmers to create executable code – Exe files. It enables programmers to develop programs that can be used as front end to databases. Besides, it’s with the help of visual basic tools, one can change the abstract ideas into programs or into the whole software while it allows revising and modifying the programs fittingly.

5

Basic Computer Coding: Visual Basic

1.1.3 Advantages and Disadvantages of Visual Basic Advantages ■

The structure of the Basic programming language is very simple, particularly as to the executable code.



VB is not only a language but primarily an integrated, interactive development environment (“IDE“).



The VB-IDE has been highly optimized to support rapid application development (“RAD”). It is particularly easy to develop graphical user interfaces and to connect them to handler functions provided by the application.



The graphical user interface of the VB-IDE provides intuitively appealing views for the management of the program structure in the large and the various types of entities (classes, modules, procedures, forms, …).



VB provides a comprehensive interactive and contextsensitive online help system.



When editing program texts the “IntelliSense” technology informs you in a little popup window about the types of constructs that may be entered at the current cursor location.



VB is a component integration language which is attuned to Microsoft’s Component Object Model (“COM”).



COM components can be written in different languages and then inegrated using VB.



Interfaces of COM components can be easily called remotely via Distributed COM (“DCOM”), which makes it easy to construct distributed applications.



COM components can be embedded in / linked to your application’s user interface and also in/to stored documents (Object Linking and Embedding “OLE”, “Compound Documents”).



There is a wealth of readily available COM components for many different purposes.

6

Introduction to Visual Basic



Visual Basic is built around the .NET environment used by all Microsoft Visual languages, so there is very little that can’t be done in Visual Basic that can be done in other languages (such as C#).

Disadvantages ■

Visual basic is a proprietary programming language written by Microsoft, so programs written in Visual basic cannot, easily, be transferred to other operating systems.



There are some, fairly minor disadvantages compared with C. C has better declaration of arrays – its possible to initialize an array of structures in C at declaration time; this is impossible in VB.

1.2 VISUAL BASIC ENVIRONMENT On start up, Visual Basic 6.0 will display the following dialog box as shown in figure 1. You can choose to start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual VB programming environment.

7

Visual Basic 1.0 for DOS was released in September 1992. The language itself was not quite compatible with Visual Basic for Windows, as it was actually the next version of Microsoft’s DOS-based BASIC compilers, Microsoft QuickBASIC compiler and the BASIC Professional Development System 7.1. The interface was barely graphical, using extended ASCII characters to simulate the appearance of a GUI.

Basic Computer Coding: Visual Basic

Figure 1: The Visual Basic Start-up Dialog Box.

In figure 2, the Visual Basic Environment consists of the ■

The Blank Form window which you can design your application’s interface.



The Project window displays the files that are created in your application.



The Properties window which displays the properties of various controls and objects that are created in your applications.

It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls are tools such as boxes, buttons, labels and other objects draw on a form to get input or display output. They also add visual appeal.

Figure 2: The Visual Basic Environment. 8

Introduction to Visual Basic

1.3 BUILDING VB APPLICATIONS Visual Basic for Applications is a programming language that is similar to Visual Basic, only it is embedded in an individual Microsoft application such as Excel or Access. Using VBA you can create macros or small programs that perform tasks within the Microsoft application.

1.3.1 Creating Your First Application First of all, launch Microsoft Visual Basic 6 compiler that you have installed earlier. In the New Project Dialog, choose Standard EXE to enter Visual Basic 6 integrated development environment. In the VB6 IDE, a default form with the name Form1 will be presented to you. Next, double click on Form1 to bring up the source code window for Form1, as shown in Figure 3. The top of the source code window consists of a list of objects and their associated events or procedures. In the source code window, the object displayed isForm1 and the associated procedure is Load.

Figure 3: The VB6 Source Code Window.

9

Basic Computer Coding: Visual Basic

When you click on the object box, the drop-down list will display a list of objects you have inserted into your form, as shown in figure 4. Here, you can see a form with the name Form1, a command button with the name Command1, a Label with the name Label1 and a Picture Box with the name Picture1.

Figure 4: List of Objects.

Similarly, when you click on the procedure box, a list of procedures associated with the object will be displayed, as shown in Figure 5. Some of the procedures associated with the object Form1 are Activate, Click, DblClick (which means Double-Click), DragDrop, keyPress and more. Each object has its own set of procedures. You can always select an object and write codes for any of its procedure in order to perform certain tasks.

Figure 5: List of Procedures. 10

Introduction to Visual Basic

You do not have to worry about the beginning and the end statements (i.e. Private Sub Form_Load.......End Sub.); Just key in the lines in between the above two statements exactly as are shown here. When you press F5 to run the program, you will be surprised that nothing showed up .In order to display the output of the program, you have to add the Form1.show statement like in Example 1 or you can just use Form_Activate ( ) event procedure as shown in example 2. The command Print does not mean printing using a printer but it means displaying the output on the computer screen. Now, press F5 or click on the run button to run the program and you will get the output as shown in Figure 6.

Example 1 Private Sub Form_Load ( ) Form1.show Print “Welcome to Visual Basic tutorial” End Sub Example 2 Private Sub Form_Activate ( ) Print 20 + 10 Print 20 - 10 Print 20 * 10 Print 20 / 10 End Sub

11

Basic Computer Coding: Visual Basic

Figure 6: The output of Example 1.

Figure 6: The output of Example 2.

This snippet makes a counter that moves up 1 every second (a label and a timer control need to be added to the form for this to work) until the form is closed or an integer overflow occurs: Option Explicit Dim Count As Integer Private Sub Form_Load() Count = 0 Timer1.Interval = 1000 ‘ units of milliseconds

12

Introduction to Visual Basic End Sub Private Sub Timer1_Timer() Count = Count + 1 Label1.Caption = Count End Sub

1.3.2 Steps in Building a Visual Basic Application Step 1: Design the interface by adding controls to the form and set their properties Step 2: Write code for the event procedures

Example 3 Changing Background and Foreground Color at Random In this example, we want to show you how to write code to change the background and the foreground color randomly. We will place two command buttons and a label on the form. One of the command buttons will be used to change the background color while the other one will be used to change the foreground color. The Label is for displaying the foreground color. There are two events here, change background color and change foreground color. Therefore, we need to write code for the two event procedures. To make the program more interesting, we will use the Rnd() function, the Int() function and the RGB codes to change the color randomly. The Rnd() function creates a random number between 0 and 1 and the RGB code uses a combination of three integers to form a certain color. The Int() is a function that converts a number into an integer by truncating its decimal part and the resulting integer is the largest integer that is smaller than the number. For example, Int(0.2)=0, Int(2.4)=2, Int(4.8)=4. Therefore, Int(Rnd()*256) returns the smallest integer 0 and the biggest integer 255. The format of RGB code is RGB(a,b,c), where a, b, c range from 0 to 255. For example, RGB(255,0,0) is red, RGB(255,255,255) is white and (0,0,0) is black. 13

Basic Computer Coding: Visual Basic

Now, rename the controls as follows: ■

Form1-MyForm



Label1-LblMessage



Command1-cmd_bgColor



Command2-cmd_fgColor

Next, change the caption of the Label to “Please Change My Color”. In addition, change the caption of Command1 button to “Change Background Color” and change the caption of Command2 button to “Change Foreground Color” Now, enter the following code Private Sub cmd_bgColor_Click() Dim r, g, b As Integer r = Int(Rnd() * 256) g = Int(Rnd() * 256) b = Int(Rnd() * 256) MyForm.BackColor = RGB(r, g, b) End Sub Private Sub Cmd_fgColor_Click() Dim r, g, b As Integer r = Int(Rnd() * 256) g = Int(Rnd() * 256) b = Int(Rnd() * 256) Lbl_Msg.ForeColor = RGB(r, g, b) End Sub When you run the program, each time you press on the ‘Change Background Color’ button, you will see different background color. Similarly, each time you press on the ‘Change Foreground Color’,

14

Introduction to Visual Basic

you will see the message on the Label changes color. The output is shown in Figure 7.

Figure 7:

1.3.3 Structure of a Visual Basic Application Application (Project) is made up of: ■ ■

The user interface in the

Forms - Windows that you create for industrial design field of human–computer user interface interaction, is the space Controls - Graphical features drawn where interactions on forms to allow user interaction (text between humans and machines occur. boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are objects.)



Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time.



Methods - Built-in procedure that can be invoked to impart some action to a particular object. 15

Basic Computer Coding: Visual Basic



Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs.



General Procedures - Code not related to objects. This code must be invoked by the application.



Modules - Collection of general procedures, variable declarations, and constant definitions used by application.

1.3.4 Drawing the User Interface and Setting Properties Visual Basic operates in three modes. ■

Design mode - used to build application



Run mode - used to run the application



Break mode - application halted and debugger is available

Six windows appear when you start Visual Basic. ■

A menu bar is a graphical control element which contains drop-down menus.

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

16

Introduction to Visual Basic



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



The Toolbox is the selection menu for controls used in your application.

17

Basic Computer Coding: Visual Basic



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



The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor’s screen:

18

Introduction to Visual Basic



The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.



As mentioned, the user interface is ‘drawn’ in the form window. There are two ways to place controls on a form: •

Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize it.



Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn.



To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button.



To resize a control, click the object so that it is select and sizing handles appear. Use these handles to resize the object.

19

Basic Computer Coding: Visual Basic

1.3.5 Saving Projects Even the simplest Visual Basic project comprises multiple files which must each be saved on your system to store the project. A toolbar is a graphical control element on which on-screen buttons, icons, menus, or other input or output elements are placed.

Follow these steps to save the current New Project to disk: ■

Click the Save All button on the Tool Bar, or click File, Save All on the Menu Bar, or press the Ctr+Shift+S keys, to open the Save Project dialog

20

Introduction to Visual Basic



In the Save Project dialog you can optionally change the Project name if it is part of a larger Solution – for simple applications just leave the Project name the same as the Solution Name



Choose a Location at which to save your project, or accept the suggested Location



Ensure that the “Create directory for solution” box is checked, then click the Save button to save all your project files

21

Basic Computer Coding: Visual Basic

ROLE MODEL Alan Cooper: Father of Visual Basic Born in San Francisco in 1952 and raised in Marin County, California, Alan Cooper has always taken the path less traveled. A rebellious teenager, he dropped out of high school, but eventually made his way to the College of Marin to pursue his interest in architecture. After an exploratory course in programming, it became clear that his future was in architecture—software architecture. After getting his associate degree and a COBOL programming job, he saw an advertisement for one of the first personal computers and conceived an idea for a new business venture. In 1976, Cooper founded Structured Systems Group (SSG), a company Fire in the Valley authors Paul Freiberger and Michael Swaine said created “the first serious business software for microcomputers.” In four years, Cooper wrote and shipped a dozen application programs. SSG became the archetype for many software startups in the early days of the personal computer revolution. During the 1980s, after leaving SSG, Cooper invented, wrote, and sold three major software packages to prominent publishers. One of those was the visual programming front-end code named “Ruby,” for what became Visual BASIC. Bill Gates purchased it from Cooper in 1988, noting that it would have significant impact across Microsoft’s entire product line. Visual BASIC was deemed both a commercial and critical success, earning Cooper the moniker “Father of Visual BASIC.” Visual BASIC has influenced integrated development languages ever since. In 1990 Cooper became fascinated with the challenge of making software products that were easy to use and understand. He and his wife, Susan, founded Cooper Interaction Design (now “Cooper”) to assist in what Cooper calls “interaction design.” In the design field, Cooper’s software development background was unique and, over the next few years, he invented many of the tools and techniques now standard in the user experience industry, including personas 22

Introduction to Visual Basic

and scenarios, pair design, and possibility thinking. He calls this ensemble “goal-directed design.” In the 1990s, Cooper published two books on interaction design, About Face and The Inmates are Running the Asylum, which have become required reading for practitioners. While Alan still leads Cooper as a director, he and his wife have moved to a former dairy ranch in Petaluma, California. Cooper has become a vocal advocate for sustainable and regenerative agriculture, not coincidentally pointing out the parallels between ethics in agribusiness and ethics in the software business. In 1995 Bill Gates awarded Cooper the first of only seven Windows Pioneer awards in recognition of Cooper’s contributions to the success of the Windows operating system. In 1998 the Silicon Valley Forum awarded Cooper one of its first Visionary Awards for his ongoing contributions.

23

Basic Computer Coding: Visual Basic

SUMMARY ■

Visual Basic is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners’ Allpurpose Symbolic Instruction Code. It is a fairly easy programming language to learn. The codes look a bit like English Language.



Visual Basic is a programming language and development environment created by Microsoft. It is an extension of the BASIC programming language that combines BASIC functions and commands with visual controls. Visual Basic provides a graphical user interface GUI that allows the developer to drag and drop objects into the program as well as manually write program code.



The Properties window which displays the properties of various controls and objects that are created in your applications.



Visual Basic for Applications is a programming language that is similar to Visual Basic, only it is embedded in an individual Microsoft application such as Excel or Access. Using VBA you can create macros or small programs that perform tasks within the Microsoft application.



The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form.

24

Introduction to Visual Basic

KNOWLEDGE CHECK 1.

2.

3.

4.

5.

Visual Basic is a tool that allows you to develop application in………… a.

Real time

b.

Graphical User Interface

c.

Menu Driven

d.

None Of These

Microsoft’s Visual Basic language were launched early in a.

1960s

b.

1970s

c.

1980s

d.

1990s

Which windows displays a list of all forms and modules making up your application a.

Project window

b.

Properties window

c.

Form layout window

d.

All of the above

When the user clicks a button, _________ is triggered. a.

an event

b.

a method

c.

a setting

d.

a property

Which of the following windows is the central to the development of Visual Basic applications a.

Project window

b.

Form window

c.

Properties window

d.

All of the above

25

Basic Computer Coding: Visual Basic

REVIEW QUESTIONS 1.

What is visual basic? Why are importance of visual basic programming language?

2.

What is visual basic environment?

3.

Describe the structure of a visual basic application.

4.

How to creating your first application?

5.

Discuss the saving projects in VB.

Check Your Result 1. (b)

2. (d)

3. (a)

26

4. (a)

5. (b)

Introduction to Visual Basic

REFERENCES 1.

https://www.techopedia.com/definition/3962/visual-basicvb

2.

https://searchwindevelopment.techtarget.com/definition/ Visual-Basic

3.

http://ceng.anadolu.edu.tr/emrekacmaz/bil158/VBTutorial. pdf

4.

https://www.cleverism.com/skills-and-tools/visual-basic/

5.

https://www.thoughtco.com/about-vib-and-about-thissite-3424549

6.

https://www.encyclopedia.com/science-and-technology/ computers-and-electrical-engineering/computers-andcomputing/visual-basic

7.

https://techterms.com/definition/visualbasic

8.

https://www.visualchart.com/ContentManagement/ Development/Manuals/EN/vbNet_programming.pdf

9.

https://upload.wikimedia.org/wikipedia/commons/b/b8/ Visual_basic_6.0.pdf

10.

https://www.chegg.com/homework-help/definitions/thevisual-basic-environment-3

11.

http://ineasysteps.com/wp-content/uploads/2012/06/ HowtoSaveProjectsinVisualBasic.pdf

12.

https://msdn.microsoft.com/en-us/library/ee256753.aspx

13.

https://social.msdn.microsoft.com/Forums/vstudio/enUS/10ca93b4-4f96-4f5c-a30b-939b71be441f/faq-item-howdo-i-save-an-existing-project-to-different-local-locationvia-ide-menu?forum=vbgeneral

14.

https://www.vbtutor.net/lesson2.html

15.

https://www.csus.edu/indiv/s/scanland/mis15/index_htm_ files/ch2.pdf

16.

https://docs.microsoft.com/en-us/visualstudio/ide/step-1create-a-windows-forms-application-project?view=vs-2017

27

Basic Computer Coding: Visual Basic

17.

https://iiteeeestudents.wordpress.com/2011/08/28/ advantages-and-disadvantages-of-visual-basic/

18.

https://www.linkedin.com/pulse/visual-basic-importanceprogramming-language-fareed

28

CHAPTER 2

DATA TYPES, CONSTANTS AND VARIABLES “Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” ―Rick Cook

Learning Objectives After studying this chapter, you will be able to: ■

Learn about the data types



Explain the useful variable in visual basic



Know about the constants in visual basic

Basic Computer Coding: Visual Basic

INTRODUCTION A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers. The data type defines which operations can safely be performed to create, transform and use the variable in another computation. When a program language requires a variable to only be used in ways that respect its data type, that language is said to be strongly typed. This prevents errors, because while it is logical to ask the computer to multiply a float by an integer (1.5 x 5), it is illogical to ask the computer to multiply a float by a string (1.5 x Alice). When a programming language allows a variable of one data type to be used as if it were a value of another data type, the language is said to be weakly typed. Technically, the concept of a strongly typed or weakly typed programming language is a fallacy. In every programming language, all values of a variable have a static type -- but the type might be one whose values are classified into one or more classes. And while some classes specify how the data type’s value will be compiled or interpreted, there are other classes whose values are not marked with their class until run-time. The extent to which a programming language discourages or prevents type error is known as type safety. A variable is a named memory location which temporarily stores data that can change while the program is running. A variable is something that may change in value. A variable might be the number of words on different pages of this booklet, the air temperature each day, or the exam marks given to a class of school children. A variable could be likened to a storage box whose contents may often change. The box, or variable must be given a name to distinguish it from others. A constant is a value that never changes. The other type of values that programs use is variables, symbols that can represent different values throughout the course of a program.

30

Data Types, Constants and Variables

A constant can be •

a number, like 25 or 3.6



a character, like a or $



a character string, like “this is a string”

Constants are also used in spreadsheet applications to place nonchanging values in cells. In contrast, a spreadsheet formula can produce a different value each time the spreadsheet is opened or changed.

2.1 DATA TYPES All programs are composed of two items: Data and Operations on that Data. Because, at their heart, computers are simple devices, they can only represent very simple pieces of information. All complex information must be built up from these basic Data Types. The data types can roughly be described as: numbers, Booleans, characters, arrays, and structures. Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The following table shows the Visual Basic data types, their supporting common language runtime types, their nominal storage allocation, and their value ranges. Visual Basic type

Common language runtime type structure

Nominal storage allocation

Value range

Boolean

Boolean

Depends on implementing platform

True or False

Byte

Byte

1 byte

0 through 255 (unsigned)

Char(single character)

Char

2 bytes

0 through 65535 (unsigned)

31

Basic Computer Coding: Visual Basic Date

DateTime

8 bytes

0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999

Decimal

Decimal

16 bytes

0 through +/-79,228, 162,514,264, 337,593, 543,950,335 (+/-7.9... E+28) † with no decimal point; 0 through +/-7.9228162514 264337593543950335 with 28 places to the right of the decimal; smallest nonzero number is +/0.000000000 0000 000000000000001 (+/-1E-28) †

Double(doubleprecision floatingpoint)

Double

8 bytes

-1.79769313486231570E+308 through -4.94065645841246544E324 † for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 † for positive values

Integer

Int32

4 bytes

-2,147,483,648 through 2,147,483,647 (signed)

Long (long integer)

Int64

8 bytes

-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 (9.2... E+18 †) (signed)

Object

Object(class)

4 bytes on 32bit platform 8 bytes on 64-bit platform

Any type can be stored in a variable of type Object

SByte

SByte

1 byte

-128 through 127 (signed)

Short(short integer)

Int16

2 bytes

-32,768 through 32,767 (signed)

Single(singleprecision floatingpoint)

Single

4 bytes

-3.4028235E+38 through -1.401298E-45 † for negative values; 1.401298E-45 through 3.4028235E+38 † for positive values

String(variablelength)

String(class)

Depends on implementing platform

0 to approximately 2 billion Unicode characters

UInteger

UInt32

4 bytes

0 through 4,294,967,295 (unsigned)

32

Data Types, Constants and Variables ULong

UInt64

8 bytes

0 through 18,446,744,073,709,551,615 (1.8... E+19 †) (unsigned)

UserDefined(structure)

(inherits from ValueType)

Depends on implementing platform

Each member of the structure has a range determined by its data type and independent of the ranges of the other members

UShort

UInt16

2 bytes

0 through 65,535 (unsigned)

In scientific notation, “E” refers to a power of 10. So 3.56E+2 signifies 3.56 x 102 or 356, and 3.56E-2 signifies 3.56 / 102 or 0.0356.



2.1.1 Memory Consumption When you declare an elementary data type, it is not safe to assume that its memory consumption is the same as its nominal storage allocation. This is due to the following considerations: ■

Storage Assignment. The common language runtime can assign storage based on the current characteristics of the platform on which your application is executing. If memory is nearly full, it might pack your declared elements as closely together as possible. In other cases it might align their memory addresses to natural hardware boundaries to optimize performance.



Platform Width. Storage assignment on a 64-bit platform is different from assignment on a 32-bit platform.

2.1.2 Composite Data Types The same considerations apply to each member of a composite data type, such as a structure or an array. You cannot rely on simply adding together the nominal storage allocations of the type’s members. Furthermore, there are other considerations, such as the following: ■

Overhead. Some composite types have additional memory requirements. For example, an array uses extra memory for the array itself and also for each dimension. On a 32-bit platform, this overhead is currently 12 bytes plus 8 bytes for each dimension. On a 64-bit platform this requirement is doubled. 33

Basic Computer Coding: Visual Basic



Storage Layout. You cannot safely assume that the order of storage in memory is the same as your order of declaration. You cannot even make assumptions about byte alignment, such as a 2-byte or 4-byte boundary. If you are defining a class or structure and you need to control the storage layout of its members, you can apply the StructLayoutAttribute attribute to the class or structure.

2.1.3 Boolean Data Type Holds values that can be only True or False. The keywords True and False correspond to the two states of Boolean variables. Use the Boolean Data Type (Visual Basic) to contain two-state values such as true/false, yes/ no, or on/off. The default value of Boolean is False. Boolean data type is a data type that has one of two possible values (usually denoted true and false), intended to represent the two truth values of logic and Boolean algebra.

Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should restrict usage of Boolean variables to the logical values for which they are designed.

Type Conversions When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True. When Visual Basic converts Boolean values to numeric types, Falsebecomes 0 and True becomes -1. When you convert between Boolean values and numeric data types, keep in mind that the .NET Framework conversion methods do 34

Data Types, Constants and Variables

not always produce the same results as the Visual Basic conversion keywords. This is because the Visual Basic conversion retains behavior compatible with previous versions. For more information, see “Boolean Type Does Not Convert to Numeric Type Accurately” in Troubleshooting Data Types.

Programming Tips ■

Negative Numbers. Boolean is not a numeric type and cannot represent a negative value. In any case, you should not use Boolean to hold numeric values.



Type Characters. Boolean has no literal type character or identifier type character.



Framework Type. The corresponding type in the .NET Framework is the System. Boolean structure.

Example: In the following example, running VB is a Boolean variable, which stores a simple yes/no setting. Dim runningVB As Boolean ‘ Check to see if program is running on Visual Basic engine. If scriptEngine = “VB” Then runningVB = True End If

2.1.4 Byte Data Type Holds unsigned 8-bit (1-byte) integers that range in value from 0 through 255. Use the Byte data type to contain binary data. The default value of Byte is 0.

Programming tips ■

Negative Numbers. Because Byte is an unsigned type, it cannot represent a negative number. If you use the unary minus (-) operator on an expression that evaluates to type Byte, Visual Basic converts the expression to Short first.



Format Conversions. When Visual Basic reads or writes 35

Basic Computer Coding: Visual Basic

files, or when it calls DLLs, methods, and properties, it can automatically convert between data formats. Binary data stored in Bytevariables and arrays is preserved during such format conversions. You should not use a String variable for binary data, because its contents can be corrupted during conversion between ANSI and Unicode formats. ■

Widening. The Byte data type widens to Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, or Double. This means you can convert Byte to any of these types without encountering a System.OverflowException error.



Type Characters. Byte has no literal type character or identifier type character.



Framework Type. The corresponding type in the .NET Framework is the System.Byte structure.

Example: In the following example, b is a Byte variable. The statements demonstrate the range of the variable and the application of bit-shift operators to it. ‘ The valid range of a Byte variable is 0 through 255. Dim b As Byte b = 30 ‘ The following statement causes an error because the value is too large. ‘b = 256 ‘ The following statement causes an error because the value is negative. ‘b = -5 ‘ The following statement sets b to 6. b = CByte(5.7)

‘ The following statements apply bit-shift operators to b. ‘ The initial value of b is 6. 36

Data Types, Constants and Variables

Console.WriteLine(b) ‘ Bit shift to the right divides the number in half. In this ‘ example, binary 110 becomes 11. b >>= 1 ‘ The following statement displays 3. Console.WriteLine(b) ‘ Now shift back to the original position, and then one more bit ‘ to the left. Each shift to the left doubles the value. In this ‘ example, binary 11 becomes 1100. b Add Query menu option. In the Search Criteria Builder dialog change the New Query Name to France and click on the Query Builder button. In the Query Builder dialog, scroll down the table until you reach the Country column. Scroll horizontally until you reach the Filter field and TextBox is a composite enter France as the filter criteria:

control that is composed of several encapsulated components.

211

Basic Computer Coding: Visual Basic

Click on OK. Visual Studio will generate the appropriate SQL statement to perform this query. SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (Country = ‘France’) Press F5 to rebuild and run the application. An additional toolbar now appears labeled France which, when pressed, filters the database entries so that only customers in France are selected:

212

Data Access

ROLE MODEL Edgar F. Codd Edgar Frank “Ted” Codd (19 August 1923 – 18 April 2003) was an English computer scientist who, while working for IBM, invented the relational model for database management, the theoretical basis for relational databases and relational database management systems. He made other valuable contributions to computer science, but the relational model, a very influential general theory of data management, remains his most mentioned, analyzed and celebrated achievement.

Biography Edgar Frank Codd was born in Fortuneswell, on the Isle of Portland in Dorset, England. After attending Poole Grammar School, he studied mathematics and chemistry at Exeter College, Oxford, before serving as a pilot in the RAF Coastal Command during the Second World War, flying Sunderlands. In 1948, he moved to New York to work for IBM as a mathematical programmer. In 1953, angered by Senator Joseph McCarthy, Codd moved to Ottawa, Ontario, Canada. In 1957 he returned to the US working for IBM and from 1961–1965 pursuing his doctorate in computer science at the University of Michigan in Ann Arbor. Two years later he moved to San Jose, California, to work at IBM’s San Jose Research Laboratory, where he continued to work until the 1980s. He was appointed IBM Fellow in 1976. During the 1990s, his health deteriorated and he ceased work. Codd received the Turing Award in 1981, and in 1994 he was inducted as a Fellow of the Association for Computing Machinery. Codd died of heart failure at his home in Williams Island, Florida, at the age of 79 on 18 April 2003.

Work Codd received a PhD in 1965 from the University of Michigan, Ann Arbor advised by John Henry Holland. His thesis was about self213

Basic Computer Coding: Visual Basic

replication in cellular automata, extending on work of von Neumann and showing that a set of eight states was sufficient for universal computation and construction. His design for a self-replicating computer was only implemented in 2010. In the 1960s and 1970s he worked out his theories of data arrangement, issuing his paper “A Relational Model of Data for Large Shared Data Banks” in 1970, after an internal IBM paper one year earlier. To his disappointment, IBM proved slow to exploit his suggestions until commercial rivals started implementing them. Initially, IBM refused to implement the relational model to preserve revenue from IMS/DB. Codd then showed IBM customers the potential of the implementation of its model, and they in turn pressured IBM. Then IBM included in its Future Systems project a System R subproject – but put in charge of it developers who were not thoroughly familiar with Codd’s ideas, and isolated the team from Codd. As a result, they did not use Codd’s own Alpha language but created a non-relational one, SEQUEL. Even so, SEQUEL was so superior to pre-relational systems that it was copied, in 1979, based on pre-launch papers presented at conferences, by Larry Ellison, of Relational Software Inc, in his Oracle Database, which actually reached market before SQL/DS – because of the thenalready proprietary status of the original name, SEQUEL had been renamed SQL. Codd continued to develop and extend his relational model, sometimes in collaboration with Christopher J. Date. One of the normalized forms, the Boyce–Codd normal form, is named after him. Codd’s theorem, a result proven in his seminal work on the relational model, equates the expressive power of relational algebra and relational calculus (both of which, lacking recursion, are strictly less powerful than first-order logic). As the relational model started to become fashionable in the early 1980s, Codd fought a sometimes bitter campaign to prevent the term being misused by database vendors who had merely added a relational veneer to older technology. As part of this campaign, he published his 12 rules to define what constituted a relational database. This made his position in IBM increasingly difficult, so he left to form his own consulting company with Chris Date and others. 214

Data Access

Codd coined the term Online analytical processing (OLAP) and wrote the “twelve laws of online analytical processing”. Controversy erupted, however, after it was discovered that this paper had been sponsored by Arbor Software (subsequently Hyperion, now acquired by Oracle), a conflict of interest that had not been disclosed, and Computerworld withdrew the paper. In 2004, SIGMOD renamed its highest prize to the SIGMOD Edgar F. Codd Innovations Award, in his honor.

215

Basic Computer Coding: Visual Basic

SUMMARY ■

Data access refers to a user’s ability to access or retrieve data stored within a database or other repository. Users who have data access can store, retrieve, move or manipulate stored data, which can be stored on a wide range of hard drives and external devices.



Data access is a feature of Visual Basic that allows you to access and manipulate any database from Visual Basic. The database may be either MS-Access database or FoxPro database or it may also be any of the relational databases such as Oracle. You can develop applications in Visual Basic that can access data in a database.



ADO.Net object model is nothing but the structured process flow through various components.



A data provider is used for connecting to a database, executing commands and retrieving data, storing it in a dataset, reading the retrieved data and updating the database.



DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are retrieved from a database. When a connection is established with the database, the data adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the database is closed. This is called the ‘disconnected architecture’. The dataset works as a virtual database containing tables, rows, and columns.



Begin by launching Visual Studio and creating a new Windows Application project called “VBdatabase”. Once the new project has been created the first task is to connect to the Northwind database. Click on the View menu and select Server Explorer.



Once the database connection is established, the next step is to select the data source to be used in the application. To achieve this, select the Data->Add New Data Source menu option.

216

Data Access

KNOWLEDGE CHECK 1.

2.

3.

4.

5.

A collection of data designed to be used by different people is called a/an a.

Organization

b.

Database

c.

Relationship

d.

Schema

Which of the following is the oldest database model? a.

Relational

b.

Deductive

c.

Physical

d.

Network

Which of the following is an attribute that can uniquely identify a row in a table? a.

Secondary key

b.

Candidate key

c.

Foreign key

d.

Alternate key

Which of the following is the process of selecting the data storage and data access characteristics of the database? a.

Logical database design

b.

Physical database design

c.

Testing and performance tuning

d.

Evaluation and selecting

Which of the following terms does refer to the correctness and completeness of the data in a database? a.

Data security

b.

Data constraint

c.

Data independence

d.

Data integrity 217

Basic Computer Coding: Visual Basic

REVIEW QUESTIONS 1.

What is the use of data provider?

2.

What is dataset? Describe the components of dataset.

3.

How to create table, columns and rows. Discuss.

4.

How to select the data source? How to link data sources to an application? Explain.

5.

How to add SQL statements to a visual basic application? Describe.

Check your Result 1. (b)

2. (d)

3. (b)

218

4. (b)

5. (d)

Data Access

REFERENCES 1.

Connolly, Thomas and Carolyn Begg. Database Systems. New York: Harlow, 2002.

2.

Hitchhiker’s Guide to Visual Studio and SQL Server (7th Edition) Addison Wesley, William Vaughn, ISBN 978-0321-24362-1

3.

https://free-visualbasic-tutor.blogspot.com/2011/07/dataaccess.html

4.

https://msdn.microsoft.com/en-us/library/ ms524771(v=vs.90).aspx

5.

https://www.techopedia.com/definition/26929/data-access

6.

https://www.techotopia.com/index.php/Accessing_ Databases_Using_Visual_Basic

7.

https://www.tutorialspoint.com/vb.net/vb.net_database_ access.htm

8.

Kroenke, David M. and David J. Auer. Database Concepts. 3rd ed. New York: Prentice, 2007.

9.

Lightstone, S.; Teorey, T.; Nadeau, T. (2007). Physical Database Design: the database professional’s guide to exploiting indexes, views, storage, and more. Morgan Kaufmann Press. ISBN 0-12-369389-6.

10.

Ling Liu and Tamer M. Özsu (Eds.) (2009). “Encyclopedia of Database Systems, 4100 p. 60 illus. ISBN 978-0-38749616-0.

11.

Teorey, T.; Lightstone, S. and Nadeau, T. Database Modeling & Design: Logical Design, 4th edition, Morgan Kaufmann Press, 2005. ISBN 0-12-685352-5

219

INDEX A ActiveX controls 89, 95, 97 ADO.Net object model 191, 192, 216 assignment statement 74, 94 B Binary data 35, 36 Boolean Data Type 34 Boolean expression 77, 78 C Case statements 75, 83 Char data type 37 Class Statement 71

command 193 Common language runtime 31, 33 Const Statement 71 Control statement 70 D Data access 192, 216 database 191, 192, 193, 194, 196, 197, 198, 200, 201, 208, 209, 210, 211, 212, 213, 214, 216, 217, 219 Database system 4 DataColumn 195, 196, 205, 207 data provider 193, 194, 216, 218 Data reader 194 DataRow 195, 196, 205, 207

Basic Computer Coding: Visual Basic

dataset 193, 194, 195, 206, 216, 218 DataSet class 195 data source 191, 193, 194, 195, 197, 200, 208, 209, 216, 218 data store 193 DataTable 195, 196, 205, 206, 207 Data type 30, 33, 34, 35, 36, 38, 39, 40, 41, 42, 45, 51, 56, 57, 58, 59, 64, 65, 67 Debugging 127, 128, 130, 131, 132, 133, 135, 137, 151, 153, 154 Debug menu 134, 135, 136, 137, 151 Debug toolbar 133 Debug window 137, 138, 139, 151, 152 Decimal data type 39 Decision making structures 74, 94 declaration statements 70, 71, 94, 97 Declare Statement 73 Delegate Statement 73 Dim Statement 71 disconnected architecture 195, 216 Drop-down 103 Dynamic array 177, 178, 179, 180, 189 E Else statement 75, 77, 79 EntityClient provider 194 Entity Data Model (EDM) 194 Enum Statement 71 Event procedure 161, 186 Event Statement 73

executable statement 73, 94 external devices 192, 216 F Floating-point data type 42 FoxPro database 192, 216 Function procedure 163 Function Statement 72 G General procedure 161, 186 Global variable 44 Graphical user interface GUI 3, 24 H hard drives 192, 216 I If statement 76, 77, 79, 81 If-Then-Else statements 81 if-then statement 76 Insertable Objects 89 Interactive development environment (\“IDE\“) 6 Interface Statement 72 intrinsic controls 88, 95, 97 L Logic errors 128, 130 M Memory consumption 33 Menu Editor 106, 108, 123 Microsoft Access 197, 198 Microsoft Access Database 197 Microsoft ActiveX Data Objects. Net (ADO.Net) 192

222

Index

Microsoft application 9, 24 Microsoft SQL Server 194, 198 Module Statement 72 MS-Access database 192, 216 Multiple Document Interface (MDI) 101, 109

Server Explorer 196, 216 Single Document Interface (SDI) 101, 109 SQL Query 211 Statements 69, 70, 71, 73, 81, 94 Static array 177 Static variable 47, 48, 49, 50 Structure Statement 72 Sub procedure 158, 159 Sub Statement 72 Syntax errors 128

O One-dimensional array 173, 187 Operator Statement 73 P Private statement 44 Procedure-level variable 44, 47 Procedure parameter 158 programming elements 71 Programming languages 156, 186 program’s execution 70 Property procedure 166, 167, 169, 186 Property Statement 73 R Rapid application development (\“RAD\”) 6 Resume keyword 146 retrieving data 193, 195, 216 Ruby Programming Language 4 Run-time errors 128 S

V VBdatabase 196, 216 Visual Basic 1, 2, 3, 4, 6, 7, 8, 9, 11, 13, 15, 16, 17, 20, 22, 24, 25, 31, 34, 35, 38, 39, 40, 42, 44, 45, 46, 50, 51, 52, 53, 55, 58, 59, 60, 64, 65, 66, 68, 70, 85, 86, 88, 89, 94, 95, 96, 98, 100, 106, 123, 156, 157, 160, 163, 166, 171, 180, 184, 186, 190, 192, 197, 210, 211, 216 Visual Basic application 192, 211 Visual Basic control 85 Visual Basic Objects 86, 94 Visual Studio Code 46 W Windows Application project 196, 216

Select Case statement 75, 82

223