Visual Basic 2015 Made Easy

Transcription

Visual Basic 2015Made EasyDr.LiewDisclaimer

Visual Basic 2015 Made Easy is an independent publication and is not affiliatedwith, nor has it been authorized, sponsored, or otherwise approved by MicrosoftCorporation.TrademarksMicrosoft, Visual Basic, Excel and Windows are either registered trademarks ortrademarks of Microsoft Corporation in the United States and/or other countries.All other trademarks belong to their respective owners.LiabilityThe purpose of this book is to provide basic guides for people interested in VisualBasic 2015 programming. Although every effort and care has been taken to makeThe information as accurate as possible, the author shall not be liable for any error,Harm or damage arising from using the instructions given in this book.Copyright 2015 Liew Voon KiongAll rights reserved. No Part of this e-book may be reproduced, in any form or by anymeans, without permission in writing from the author.

AcknowledgementI would like to express my sincere gratitude to many people who have made theircontributions in one way or another to the successful publication of this book.My special thanks go to my children Xiang, Yi and Xun who have contributed theirideas and help in editing this book. I would also like to appreciate the supportprovided by my beloved wife Kim Huang and my youngest daughter Yuan. I wouldalso like to thank the millions of readers who have visited my Visual Basic Tutorialwebsite at vbtutor.net for their support and encouragement.About the AuthorDr. Liew Voon Kiong holds a bachelor’s degree in Mathematics, a master’s degreein Management and a doctorate in Business Administration. He has been involvedin Visual Basic programming for more than 20 years. He created the popular onlineVisual Basic Tutorial at www.vbtutor.net , which has attracted millions of visitorssince 1996. It has consistently been one of the highest ranked Visual Basicwebsites.To provide more support for Visual Basic students, teachers, and hobbyists, Dr.Liew has written this book to complement the free Visual Basic 2015 tutorial withmuch more content. He is also the author of the Visual Basic Made Easy series,which includes Visual Basic 6 Made Easy, Visual Basic 2008 Made Easy, VisualBasic 2010 Made Easy, Visual Basic 2013 Made Easy, Visual Basic 2017 MadeEasy and Excel VBA Made Easy. Dr. Liew’s books have been used in high schooland university computer science courses all over the world.

1.1 A Brief Description of Visual Basic 2015111.2 The Visual Studio 2015 Integrated Development Environment131.3 Creating a New Project in Visual Studio 2015142.1 Customizing the Form20Figure 2.5242.2 Adding Controls to the Form243.1 The Concept of Event-Driven Programming293.2 Writing the Code314.1 TextBox33Example 4.14.2 Label3335Example 4.24.3 ListBox35364.3.1 Adding Items to a Listbox36Adding items using the String Collection Editor36b) Adding Items using the Add() Method38Example 4.338Example 4.439Example 4.5 Geometric Progression40Figure 4.9 The runtime interface424.3.2 Removing Items from a List Box42Example 4.542Example 4.643Example 4.644Example 4.744Example 4.8454.4 ComboBox454.4.1 Adding Items to a ComboBox464.4.2 Removing Items from a Combobox495.1 Loading an Image in a Picture Box51

5.1.1 Loading an Image at Design Time515.1.2 Loading an Image at Runtime545.2 Loading an Image in a Picture Box using Open File Dialog Control556.1 Visual Basic 2015 Data Types596.1.1 Numeric Data Types59Table 6.1: Numeric Data Types6.1.2 Non-numeric Data TypesTable 6.2: Non-numeric Data Types6.1.3 Suffixes for LiteralsTable 6.3: Non-numeric Data Types60606161616.2 Variables and Constants626.2.1 Variable Names626.2.2 Declaring Variables63Example 6.36.2.3 Assigning Values to VariablesExample 6.46465666.2.4 Scope of Declaration676.2.5 Declaring Constants677.1 Introduction to Arrays697.2 Dimension of an Array697.3 Declaring Arrays70Example 7.171Example 7.272Example 7.372Example 7.4738.1 Mathematical Operators758.2 Writing Code that Performs Mathematical Operations76Example 8.1 Standard Arithmetic Calculations76Example 8.2 Pythagorean Theorem77Example 8.3: BMI Calculator77

9.1 String Manipulation Using and & signsExample 9.19.2 String Manipulation Using Built-in Functions7979829.2 (a) Len Function82Example 9.3829.2(b) Right Function83Example 9.4839.2(c) Left Function849.2 (d) Mid Function84Example 9.584Example 9.6859.2(e) Trim Function86Example 9.7869.2(f) Ltrim Function869.2(g)The Rtrim Function879.2(h) The InStr function879.2(i) Ucase and the Lcase Functions879.2(j) Chr and the Asc functions8810.1 Conditional Operators8910.2 Logical Operators9010.3 Using If .Then.Else9110.3(a) If .Then StatementExample 10.110.3(b) If.Then Else Statement919192Example 10.292Example 10.39410.3(c) If .Then ElseIf Statement96Example 10.4 Grade Generator9611.1 The Select Case End Select Structure9811.2 The usage of Select Case is shown in the following examples99

Example 11.1: Examination Grades99Example 11.2100The output is shown in Figure 11.2101Example 11.3 Remark on Examination Results101Example 11.410212.1 For .Next Loop104Example 12.1 a105Example 12.1b105Example 12.1c105Example 12.1d10612.2 Do LoopExample 12.2(a)12.3 While .End While LoopExample 12.310610710910913.1 What is a Sub Procedure11013.2 Examples of Sub Procedure111Example 13.1111Example 13.2: Password Cracker11214.1 Creating User-Defined Functions115Example 14.1: BMI Calculator116Example 14.2: Future Value Calculator11714.2 Passing Arguments by Value and by Reference11915.1 The Abs Function122Example 15.115.2 The Exp functionExample 15.215.3 The Fix FunctionExample 15.312212312312412415.4 The Int Function12615.5 The Log Function126

Example 15.412615.6 The Rnd( ) Function127Example 15.512715.7 The Round Function129Example 15.612916.1 Format Function for Numbers13116.1(a) Built-in Format function for Numbers13116.1(b) User-Defined Format13316.2 Formatting Date and Time13516.2(a) Formatting Date and time using predefined formats13516.2(b) Formatting Date and time using user-defined formats13817.1 Check Box140Example 17.1: Shopping Cart140Example 17.2142Example 17.314217.2 Radio Button145Example 17.4145Example 17.214718.1 Introduction14918.2 Using On Error GoTo Syntax150Example 18.1: Division Errors15018.3 Errors Handling using Try .Catch .End Try Structure15219.1 Concepts of Object Oriented Programming1549.2 Creating a Class15520.1 Introduction16020.2 Creating the Graphics Object16120.3 Creating the Pen Object16220.4 Drawing a Line16220.5 Drawing Lines that Connect Multiple Points164Example 20.1165

20.6 Drawing a curve that Connect Multiple PointsExample 20.220.7 Drawing Quadratic Curve166166168Example 20.316820.8 Drawing Sine Curve170Example 20.417020.9 Drawing a Rectangle17220.10 Customizing Line Style of the Pen Object174Example 20.517420.11 Drawing an Ellipse176Example 20.6177Example 20.717820.12 Drawing a Circle179Example 20.8179Example 20.917920.13 Drawing Text180Example 20.10181Example 20.1118220.14 Drawing Polygons184Example 20.12 Drawing a Triangle185Example 20.13 Drawing a Quadrilateral18620.15 Drawing a PieExample 20.14 Drawing a pie that sweeps clockwise through 60 degree.20.16 Filling Shapes with Color20.16(a) Drawing and Filling a Rectangle with ColorExample 20.1520.16(b) Drawing and Filling an Ellipse with ColorExample 20.1620.16(c) Drawing and Filling a Polygon with Color20.16(d) Drawing and Filling a Pie187188189189189191191192193

Example 20.1819321.1 Creating a Digital Clock19621.2 Creating a Stopwatch19721.3 Creating a Digital Dice19922.1 Creating Motion20222.2 Creating a Graphical Dice20422.3 Creating a Slot Machine20723.1 Introduction to Database21023.2 Creating a Database Application21123.3 Creating Connection to a Database using ADO.NET21323.4 Populating Data in ADO.NET220Example 23.122223.5 Browsing Records22423.6 Editing, Saving, Adding and Deleting Records225Example 23.223.7 Accessing Database using DataGridViewExample 23.323.8 Performing Arithmetic Calculations in a Database226230230232Example 23.4232Example 23.5234Example 23.623524.1 Introduction23824.2 Reading a Text File23824.3 Writing to a Text File243Example 25.1: Displaying a Message248Example 25.225025.3 Creating a Text File Reader in ConsoleExample 25.325.4 Creating a Console App using If.Then.ElseExample 25.4251251252252

26.1 Creating Menu Items on the Menu Bar25526.2 Creating The Toolbar264Chapter 1Introduction to Visual Basic 2015 A brief description of Visual Basic 2015 Getting to know the Visual Basic 2015 Integrated DevelopmentEnvironment

1.1 A Brief Description of Visual Basic 2015Visual Basic is a third-generation event-driven programming language first releasedby Microsoft in 1991. The final version of the classic Visual Basic was Visual Basic6. Visual Basic 6 is a user-friendly programming language designed for beginners.Therefore, It enables anyone to develop GUI Windows applications easily. Manydevelopers still favor VB6 over its successor VB.NET.In 2002, Microsoft released Visual Basic.NET(VB.NET) to replace Visual Basic 6.Thereafter, Microsoft declared VB6 a legacy programming language in 2008.However, Microsoft still provides some form of support for VB6. VB.NET is a fullyobject-oriented programming language implemented in the .NET Framework. It wascreated to cater for the development of the web as well as mobile applications.Subsequently, Microsoft has released many versions of VB.NET. They are VisualBasic 2005, Visual Basic 2008, Visual Basic 2010 , Visual Basic 2012, Visual Basic2013 , Visual Basic 2015 and Visual Basic 201 7. Although the .NET portion wasdiscarded in 2005, all versions of the Visual Basic programming language releasedsince 2002 are regarded as VB.NET programming languageVisual Basic 2015 was released in the year 2015. It comes as a .NET desktopdevelopment component of the Visual Studio Community 2015 integrateddevelopment environment(IDE). It is used to build windows desktop applicationsusing the .NET framework. Besides that, Visual Studio Community 2015 also comeswith other Windows development tools that include Visual C#, Visual F# , VisualC , JavaScript, SQL Server, Python , Unity Game and many more.You can download the free version of Visual Studio Express 2015 for WindowsDesktop from the following ds/

After clicking the link about, you will be asked to enter your Microsoftusername and password. Next, the following window will appear, as shown inFigure 1.1Figure 1.1Select Visual Studio Express 2015 for Windows Desktop and then click thedownload button. After the installation file is downloaded, click on it to installVS Express 2015.1.2 The Visual Studio 2015 Integrated Development EnvironmentWhen you launch Microsoft Visual Studio 2015 Express, you will be presented withthe Start Page of Microsoft Visual Studio Community 2015, as shown in Figure 1.2

Figure 1.2 Visual Studio Express 2015 IDEThe Visual Studio 2015 start page comprises a few sections, the Start section andthe Recent section on the left pane and Discover Visual Studio Community 2015 onthe right pane. In the start page, you can either start a new project, open a project oropen a recent project. You can also check for the latest news in Visual StudioCommunity 2015. The Start Page also consists of a menu bar and a toolbar whereyou can perform various tasks by clicking the menu items.1.3 Creating a New Project in Visual Studio 2015To start a new Visual Studio Express 2015 project, click on New Project under theStart section to launch the Visual Studio 2015 New Project page as shown in Figure1.3. You can also choose to open a recent project:

Figure 1.3 Visual Studio 2015 Express New Project PageThe New Project Page comprises a few templates, among them are Visual Basic,Visual C# , Visual C and others. Since we are only learning Visual Basic 2015, weshall select Visual Basic. Visual Basic 2015 offers you several types of projects thatyou can create; they are Blank Apps , Windows Forms Application, WPF Application,Console Application ,Class Library(.NET Framework), Shared Project and more.Since we are only learning how to create windows desktop applications, we shallselect Windows Forms Application.At the bottom of this dialog box, you can change the default project nameWindowsApplication1 to some other name you like, for example, My First VisualBasic 2015 Program. After renaming the project, click OK to continue. The VisualBasic Express 2015 IDE Windows will appear, as shown in Figure 1.4. Visual BasicExpress 2015 IDE comprises a few windows, the Form window, the SolutionExplorer window and the Properties window. It also consists of a toolbox whichcontains many useful controls that allows a programmer to develop his or her VisualBasic 2015 programs.

Figure 1.4 The Visual Basic 2015 Express IDEThe Toolbox is not shown until you click on the Toolbox tab. When you click on theToolbox tab or use the shortcut keys Ctrl Alt x, the common controls Toolbox willappear, as shown in Figure 1.5. You can drag and move your toolbox around anddock it to the right, left ,top or bottom of the IDE.

Figure 1.5 Visual Basic 2015 Express Tool BoxNext, we shall proceed to show you how to create your first program. First, changethe text of the form to ‘My First Visual Basic 2015 Program’ in the properties window;it will appear as the title of the program. Next, insert a button and change its text toOK and its name to BtnOK. The design interface is shown in Figure 1.6Figure 1.6 The Design InterfaceNow click on the OK button to bring up the code window and enter the followingstatement between Private Sub and End Sub procedure, as shown in Figure 1.6:MsgBox( "My First Visual Basic 2015 Program" )Now click on the Start button on the toolbar or press F5 to run the program then clickon the OK button, a dialog box that displays the “My First Visual Basic 2015Program″ message will appear, as shown in Figure 1.7. The function MsgBox is abuilt-in function of Visual Basic 2015 which can display the text enclosed within thebrackets

Figure 1.7 Visual Basic 2015 Code WindowFigure 1.8 The Runtime InterfaceSummary In section 1.1, you have learned about the history of Visual Basic 2015 In section 1.2, you have learned how to install and launch Visual Basic StudioExpress 2015 In section 1.3, you have learned how to launch the new project dialog and theVisual Basic Express 2015 IDE. You have also learned how to write your firstprogram.

Chapter 2Designing the Interface Customizing Adding controls Setting Control PropertiesAs Visual Basic 2015 is a GUI-based programming language, the first step indeveloping an application is to build a graphical user interface. To build a graphicaluser interface, you need to customize the default form by changing its properties atdesign phase and at runtime. After customizing the default form, you may proceed toadd controls from the toolbox to the form and then customize their properties.2.1 Customizing the FormWhen you start a new Visual Basic 2015 project, the VS2015 IDE will display thedefault form along with the Solution Explorer window and the Properties window forthe form as shown in Figure 2.1. The name of the default form is Form1. The

properties window displays all the properties related to Form1 and theircorresponding attributes or values. You can change the name of the form, the title ofthe form using the text property, the background color, the foreground color, the sizeand more. Try changing the following properties :PropertyValueNameMyFormTextMy First Visual Basic 2015 lseIn fact, you do not have to type in the color manually, you can indeed select a colorfrom the color drop-down list that comprises three tabs, Custom, Web, and System,as shown in the Figure 2.1. Clicking on the drop-down arrow will bring out a colorpalette or a list of color rectangles where you can select a color.Figure 2.1Another method of setting the colors is to manually type in the RGB color code or thehex color code. The values of R, G and B ranges from 0 to 255, therefore, by varyingthe values of the RGB we can obtain different colors. For example, a RGB value of128, 255, 255 yield the cyan color.

On the other hand, the hex color code system usea six-digit, three- bytehexadecimal number to represent colors. The bytes represent the red, green andblue components of the color. One byte represents a number in the range 00 to FF(in hexadecimal notation), or 0 to 255 in decimal notation. For example, #0000ffrepresents the cyan color. However, when you type in the hex color code in theproperties window of VS2015, it automatically converts the color to RGB color or thecolor name. Figure 2.2 shows a list of Hex color codes and the corresponding colors.Figure 2.2 Hex Color CodesThe design interface is shown in Figure 2.3 and the runtime interface is shown inFigure 2.4. In the runtime interface, notice that the title has been changed fromForm1 to My First Visual Basic 2015 Program, background changed to aqua color ,the text OK color is dark blue and the window cannot be maximized.

Figure 2.3Figure 2.4You can also change the properties of the form at run-time by writing the relevantcodes. The default form is an object and an instant of the form can be denoted bythe name Me . The property of the object can be defined by specifying the object’sname followed by a dot or period:ObjectName.property

For example, we can set the background of the form to blue using the followingcode:Me .BackColor Color .BlueIn addition, you can also use the FromArgb method to specify the color using theRGB codes, as follows:Me .BackColor Color .FromArgb(0, 255, 0)To achieve the same interface as shown in Figure 2.3, type in the following code byclicking the form to enter the code window:Private Sub Form1 Load(sender As Object, e As EventArgs ) HandlesMyBase .LoadMe .Text "My First Visual Basic 2015 Program"Me .BackColor Color .CyanMe .MaximizeBox FalseMe .MinimizeBox TrueEnd SubIn place of cyan, you can use RGB code as follows:Me .BackColor Color .FromArgb(0,255,255)Press F5 to run the program and you will get the exact interface as that shown inFigure 2.4.In addition, you can also specify the size, the opacity and the position of the defaultform using the code, as follows:Private Sub Form1 Load(sender As Object , e As EventArgs Handles

MyBase.LoadMe .Text "My First VB2015 Project"Me .BackColor Color .BeigeMe .MaximizeBox FalseMe .MinimizeBox TrueMe . Size New Size ( 400 , 400 )Me .Opacity 0.85Me .CenterToParent()End SubThe runtime interface is as shown in Figure 2.5.translucent as the Opacity is set to 0.85 or 85%.Figure 2.52.2 Adding Controls to the FormNotice that background is

In section 2.1, we have learned how to build an initial interface in Visual Basic 2015by customizing the default form. Next, we shall continue to build the interface byadding some controls to the form. The controls are objects that consist of threeelements, namely properties, methods, and events.They can be added to the formfrom the Toolbox. Among the controls, the most common ones are the button, label,textbox, listbox, combobox, picture box, checkbox, radio button and more. Thecontrols can be made visible or invisible at runtime. However, some controls will onlyrun in the background and cannot be seen at runtime, one such control is the timer.The Toolbox is usually hidden when you start Visual Basic 2015 IDE, you need toclick View on the menu bar and then select Toolbox to reveal the tool box, as shownin Figure 2.6. You can also use shortcut keys Ctrl w x to bring out the toolbox.Figure 2.6: ToolboxYou can position the toolbox by dragging it anywhere you like while its status is setto float. You can also dock the toolbox by right-clicking on the tool box and choosedock from the pop-up menu. The docked Toolbox that appears side by side with theSolution Explorer, and as one of the tabbed windows together with the Form Designwindow and the code window, as shown in Figure 2.7.

Figure 2.7You can also dock the tool box at the bottom, below the default form, as shown inFigure 2.8. Further, you may also pin the tool box to the side bar or the bottom barby clicking on the pin icon on the menu bar of the toolbox.How and where you want to position your tool box is entirely up to you but westrongly suggest that you place the tool box alongside or at the bottom of the defaultform so that it is easy for you to add controls from the tool box into the form. Youshould never cover the form with the toolbox because it will be difficult to addcontrols to the form.

Figure 2.8Adding a control to the form is an easy task, what you need to do is double click it ordrag it onto the form. You can drag the control around in the form and you can alsoresize it.To demonstrate how to add the controls and then change their properties, we shalldesign a picture viewer. First, change the title of the default form to Picture Viewer inits properties window. Next, insert a picture box on the form and change itsbackground color to white. To do this, right click the picture box and select propertiesin the popup menu, then look for the BackColor Property as shown in the propertieswindow in Figure 2.9. Finally, add two buttons to the form and change the text toView and Close in their respective properties windows. The picture viewer is notfunctional yet until we write code for responding to events triggered by the user. Wewill deal with the programming part in the coming chapters.

Figure 2.9Summary In section 2.1, you have learned how to customize the form by changing thevalues of its properties. In section 2.2, you have learned how to add controls to the form and change theirproperties at design phase and at runtime.

Chapter 3Writing the Code Learn the basics of writing code in Visual Basic 2015In the previous chapter, we have learned how to design the user interface by addingcontrols to the form and by changing their properties. However, the user interfacealone will not work without adding code to them. In this chapter, we shall learn howto write code for all the controls so that they can interact with the events triggered bythe users. Before learning how to write Visual Basic 2015 code, let us dwell into theconcept of event-driven programming3.1 The Concept of Event-Driven ProgrammingVisual Basic 2015 is an event-driven programming language which means that thecode is executed in response to events triggered by the user actions like clicking themouse, pressing a key on the keyboard, selecting an item from from a drop-downlist, typing some words into textbox and more. It may also be an event that runs inresponse to some other program . Some of the common events in Visual Basic 2015are load, click, double-click, drag and drop, pressing the keys and more.Every form and every control you place on the form has a set of events related tothem. To view the events, double-click the control (object) on the form to enter thecode window. The default event will appear at the top part on the right side of thecode window. You need to click on the default event to view other events associatedwith the control. The code appears on the left side is the event procedure associatedwith the load event. Figure 3.1 illustrates the event procedure load associated withthe Form (its name has been changed to PicViewer therefore you can see the wordsPicViewer events) and Figure 3.2 shows the events associated with button.

Figure 3.1: Events associated with FormFigure 3.2: Events associated with the button

3.2 Writing the CodeTo start writing code in Visual Basic 2015, click on any part of the form to go into thecode window as shown in Figure 3.1. The event procedure is to load Form1 and itstarts with the keywords Private Sub and ends with End Sub . This procedureincludes the Form1 class and the event Load, and they are bind together with anunderscore, i.e. Form Load . It does nothing other than loading an empty form. Tomake the load event does something, insert the statement.MsgBox ( "Welcome to Visual Basic 2015″)The CodePublic Class Form1Private Sub Form1 Load(sender As Object, e As EventArgs ) HandlesMyBase .LoadMsgBox ( "My First Visual Basic 2015 Program" , , "My Message" )End SubEnd ClassMsgBox is a built-in function that displays a message in a pop-up message box. Thefunction comprises a few arguments, the first is the message that is displayed andthe third is the title of the message box. Running the program produces the message“My First Visual Basic 2015 Program” , as shown in Figure 3.3.Figure 3.3

You will notice that above Private Sub structure there is a preceding keyword PublicClassForm1 .Thisisthe concept of an object oriented programminglanguage. When we start a windows application in Visual Basic 2015, we will see adefault form with the name Form1 appears in the IDE, it is actually the Form1 Classthat inherits from the Form class System.Windows.Forms.Form . A class has eventsas it creates an instant of a class or an object.You can also write code to perform arithmetic calculation. For example, you can usethe MsgBox and the arithmetic operator plus to perform addition of two numbers, asshown below:Private Sub Form1 Load(sender As Object , e As EventArgs ) HandlesMyBase .LoadMsgBox( "2" & " " & "5" & " " & 2 5)End Sub*The symbol & (ampersand) is to perform string concatenation. The output is asshown in Figure 3.4.Figure 3.4Summary In section 3.1, you have learned the concepts of event driven programming In section 3.2, you have learned how to write code for the controls

Visual Basic is a third-generation event-driven programming language first released by Microsoft in 1991. The final version of the classic Visual Basic was Visual Basic 6. Visual Basic 6 is a u