Introduction To VB - Net 2

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 84

Visual Basic.

NET

COSC 226
TOPIC: Introduction to Visual Basic .NET
Required Text/Software:

 Programming Visual Basic.NET by Joshua J.V., Adegbenjo A.A.

 Microsoft Visual Studio 2012/2019/2022


Outline:

 What is VB.NET?
 Features of VB.Net
 The .NET Framework
 Microsoft Visual Studio.NET environment.
 VB.NET – Program Structure
What is VB.NET
 Visual Basic .NET (VB.NET) is an object-oriented computer
programming language implemented on the .NET Framework.

 It is a simple, high-level, object-oriented programming language


developed by Microsoft in 2002.

 It is a successor of Visual Basic 6.0, that supports the OOPs


concept, such as abstraction, encapsulation, inheritance, and
polymorphism.
Features of VB.NET
 It is an object-oriented programming language. Everything in
VB.NET programming will be treated as an object.
 VB.NET is used to design user interfaces for window, mobile, and
web-based applications.
 It supports a Rapid Application Development (RAD) tool kit.
Various code automatically comes from its libraries.
 It is not a case sensitive language like other languages such as C++,
java, etc.
 It supports Boolean condition for decision making in programming.
 It also supports the multithreading concept, in which you can do
multiple tasks at the same time.
Features of VB.NET
 It provides simple events management in .NET application.
 It reduces code complexity through code functionality inheritance by similar objects.
 Automatic initialized a garbage collection.
 It follows a structured and extensible programming language for error detection and
recovery.
 Conditional compilation and easy to use generic classes.
 It is useful to develop web, window, and mobile applications.
 Standard Library
 Properties and Events
 Evolved from DOS version – BASIC(Beginers’ All-purpose Symbolic Instruction Code)
 Visual and event driven programming language
 GUI support
The .NET Framework
 The .NET Framework is a software development platform that was
introduced by Microsoft in the late 1990.
 It is a virtual machine that provide a common platform to run an
application that was built using the different language such as C#,
VB.NET, Visual Basic, etc.
 It is also used to create a form based, console-based, mobile and web-
based application or services that are available in Microsoft environment.
 The .Net framework consists of an enormous library of codes used by the
client languages like VB.Net.
 The .Net framework applications are multi-platform applications such as:
 Windows applications
 Web applications
 Web services
Components of .NET Framework
• A Microsoft development platform
consist of 3 main parts:
• Compilers(VB, C#, C++, J#)
• Common Language Runtime (CLR)
• Framework Class Library (FCL)
• CLR
• Connect files from .NET compilers,
translate to executable file and manage
the execution.
• CLR consist of the following 3
components:
• Common Type System(CTS)
• Common Language Specification (CLS)
• Just-In Time Compiler (JIC)

Microsoft .NET framework


Components of .NET Framework
• CTS – defines .NET standard data type for all .NET
programming languages
• CLS – define rules for language interoperability
such as naming, data type definition
• JIT - translates IL(Intermediate Language) into
executable, processor specific machine language.

• Framework class library(FCL)


• FCL consist of approx. 100 assemblies each with
one or more classes
• Each class has methods that you invoke to
perform a task
• E.g Math class has pow and sqrt methods that
perform exponentiation and square root of value
respectively.
• Classes are organized logically into namespaces .NET FCL Namespaces
• Use import statement to tell the compiler the
specific namespace to access
• Namespaces are arranged into hierarchy as shown
below:
• Below are examples of selected namespaces
Integrated Development Environment (IDE) For VB.Net
• Microsoft provides the following development tools for VB.Net
programming:
• Visual Studio (VS)
• Visual Basic Express (VBE)
• Visual Web Developer
• Visual Basic Express and Visual Web Developer are free and a trimmed
down versions of Visual Studio. They have the same look and feel and
retain most features of Visual Studio.
• Using these tools, you can write all kinds of VB.Net programs from simple
command-line applications to more complex applications.
• Visual Studio is the tool we will be using.
What is Visual Studio?
• Visual Studio is an integrated development environment(IDE)
• Provides everything needed to create, test, and debug software
including:
• The Visual Basic language
• Form design tools to create the user interface
• Debugging tools to help find and correct programming errors
• Visual Studio can be used to create applications with other languages
such as C++ and C#
The Visual Studio Environment
• The Visual Studio environment consists of a number of
windows
• The Designer Window
• Used to create an application’s graphical user interface
• The Solution Explorer Window
• Allows you to navigate among the files in a Visual
Basic project
• The Properties Window
• Used to examine and change a control’s properties
Creating VB.NETProject
Steps in creating project
• Open the Visual Studio IDE and follow the steps below
Creating VB.NETProject
Microsoft have decided to do away with the nice start up page from 2019 versions.
Instead, you'll see something like this:
Creating VB.NETProject
Any projects you create will appear on the left, under Open recent, and you can simply click
on your file to open it.
Click on Create a new project, the fourth box on the right in the image above.
You will see the screen below:
Creating VB.NETProject
You’ll have opportunity to pick the language, platform and project type as shown below:
Creating VB.NETProject
Click Next, you'll see this screen to configure your new project:
Creating VB.NETProject
Then, you have the Visual Studio environment:
VB.NET – Program Structure

A VB.NET define the following


structure to create a program:
• Namespace declaration
• A class or module
• One or more procedures
• Variables
• The Main procedure
• Statements & Expressions
• Comments
Analysis of the program
• Line 1: Imports System is used to include the System namespace in the program.
• Line 2: It is a Module declaration, module Hello_Program. VB.Net is completely object oriented, so every program must contain a module of
a class that contains the data and procedures that your program uses.
• Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they
define the behavior of the class. A procedure could be any of the following:
• Function
• Sub
• Operator
• Get
• Set
• AddHandler
• RemoveHandler
• RaiseEvent
• Line 3: Sub Main() defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the
module or class will do when executed.
• The Main procedure specifies its behavior with the statement
• Console.WriteLine ("Hello, Welcome to the World of VB.NET") and Console.WriteLine (“Press any key to continue…") cause the messages
in the bracket to be displayed on the screen. WriteLine is a method of the Console class defined in the System namespace.
• The last line Console.ReadKey() will prevent the screen from running and closing quickly when the program is launched from Visual
Studio .NET.
• End Sub and End Module are used to terminate the subroutine and the module respectively.
Visual Basic Standard Modules
• A module is a global Visual Basic file that contains only code
– General purpose procedures, functions, and declarations of variables and
constants
– Can be accessed by all code in the same project
– No event handlers
– Stored in files that end with the .vb extension
– Appears in the Solution Explorer window along with entries for the project’s
form files
Visual Basic Standard Modules cont.
• The Module has the following characteristics:
• Modules
• contain a method named Sub Main() that can be used as the starting
point of the application. Note this applies to both Console Applications
and Windows Applications.
• contain variable declarations, functions & procedures or source code
ONLY! No forms!
• are a good place to put program code that may be common to several
forms or other modules.
• are like forms but without the visual!
• When you create a Console Application, Visual Basic automatically
creates a Module where you can begin entering your code:
Code Editor for Console Application
• For a Console Application, the code editor in invoked immediately to
allow you to enter code in the Module.
• Simply begin entering code in the Module Document.
• The Code Editor screen contains two drop-down list boxes, one for
the Object you are coding and the other for the Methods & Event-
Procedures associated with the object:
Code Editor for Console Application cont.
Main Screen for Windows
Application
Module Names and Module Files
• A module
– begins with a Module statement
– ends with an End Module statement
• Here is the general format:

• ModuleName is the name of the module


– For e.g Module1 above is the default module name
– Can be any valid identifier that describes its purpose
• Code is stored in a file that is named with the .vb extension
• Normally, the name of the file is the same as the name of the module
Module Example

• The following code shows the contents of a module named


RetailMath

• Procedures, functions, and declarations can be declared as Private,


which means that they can be accessed only by code in the same
module
How VB Organise Program or Application Files

• When you create a VB program a Folder is automatically


created in you computer which contains the files of the
program.
• A Visual Basics application is called a Solution. The Solution
is composed of one or more Project.
• The table below lists several important files and their file
extensions:
How VB Organise Program or Application Files cont.

File Explanation Example


Extension
.sln Solution – File that holds information VideoManagement.sln
about all the projects in the application

.vb Object File – Contain definition and code frmLoginScreen.vb


for Forms, Modules, Class Modules etc. MainModule.vb

Resource File – This is a resource file for


.resx the Forms in the project. It contains frmLoginScreen.resx
information about all resources used by
the form.

Project File – This file describes the


project and lists the files included in
.vbproj the project. VideoManagement.vbproj
• Visual Basic has three distinct modes:
• Design Time – When you design the User Interface (GUI) and writing the
code.
• Run Time – When you execute and test the program
• Break Time – When you have Run time errors and you stop execution
Build or Compile the Program
• The steps to build are as follows:
• 1) In the Menu Bar select Build|Build Solution, this will
invoke the Output Window
• 2) The Output Window displays the results of the
Compiler process. It shows if the results of the compiler
were successful or failed. For a fully compiled program, all
compiler errors must equal to 0
Execute or Run the Program
• Console Application where Output Window stays displayed:
• To run or execute the program do any of the following:
• The three methods to executes are:
• 1) In the Menu Bar Debug|Start Without Debugging.
• 2) Or using the keyboard use the Crtl-F5.
• 3) Or navigate to the project folder\bin directory and double-click on the
executable file
Programming Errors
• There are three varieties of programming errors:
• Syntax Errors – Errors generated due to the code not following the
rules of the language
• These errors usually involve improper punctuation, spelling or format
• These problems are easier to solve since the compiler identifies the
erroneous statement and you just have to review
• the rules of the language to make sure you are writing the statement properly
Programming Errors cont.
• Run Time Errors – Program halts during execution. The program
passed the syntax test but fails during execution. .
• These problems are usually caused by improper arithmetic execution,
attempting to access recourses that are not available etc
• These problems are difficult to solve since they only show up when the
program runs.
Programming Errors cont.
• Logical Error – The program is not doing what is supposed to do. .
• The algorithm fails to solve the problem the program was written to resolve
• These problems are even more difficult to solve since you need to re-think
and go back to the planning phase and review the Algorithm.
Assignment

Download and installed the latest version of VB.NET


VB.NET

COSC 226

Topic: Developing Windows Application


Introduction
• The main purpose of Visual Basic .NET is to develop windows and web
applications.
• The part of these applications that users interact with is known as the
user interface.
• A graphical user interface or GUI consists of one or more windows.
• A window is a rectangular area that contains other visual elements
such as text and buttons.
• The Visual Studio integrated development environment (IDE) includes
all the tools you need to create a Windows Forms app with several
visual elements.
Event-Driven Programming
• The G U I environment is event-driven
– An event is an action that takes place within a program
– All Visual Basic controls are capable of detecting various events, such
as:
 Clicking a Button control
 Changing the text in a TextBox control
• In order for a control to respond to a specific event, you must write a
special type of procedure called an event handler
– Event handlers are also known as event procedures(To be discussed
later)
Objects and Controls
• Visual Basic is an object-oriented programming (OOP) language
• An object is an item in a program that contains data and has the ability to perform
actions
• The data an object contains is referred to as properties, or attributes
• The operations/actions that an object can perform are called methods
• A method is a special type of procedure that belongs to an object

• A control is specific type of object that usually appears in a program’s


graphical user interface.
Types of Controls
VB.Net - Basic Controls
• An object is a type of user interface
element you create on a Visual Basic
form by using a toolbox control. In
fact, in Visual Basic, the form itself is
an object.
• Every Visual Basic control consists of
three important elements −
• Properties which describe the object,
• Methods cause an object to do
something and
• Events are what happens when an
object does something.
Control Properties
• A property is a value or characteristic held by
a Visual Basic object, such as Caption or Fore
Color.
• All the Visual Basic Objects can be moved,
resized or customized by setting their
properties.
• Properties can be set at design time by using
the Properties window or at run time by using
statements in the program code.
Object. Property = Value
Where
• Object is the name of the object you're customizing.
• Property is the characteristic you want to change.
• Value is the new property setting.
TextBox1.Text = “Babcock University“

TextBox1.Width = 150
Control Methods
• A method is a procedure created as a member of a class and they cause
an object to do something.
• Methods are used to access or manipulate the characteristics of an object
or a variable.
• There are mainly two categories of methods you will use in your classes:
• If you are using a control such as one of those provided by the Toolbox, you can call
any of its public methods. The requirements of such a method depend on the class
being used.
• If none of the existing methods can perform your desired task, you can add a method
to a class.

• For example, the MessageBox control has a method named Show.


MessageBox.Show("Hello, World")
Control Events
• An event is a signal that informs an application that something
important has occurred.
• When an event is initiated, a procedure called that handles the event.
• Control events include click, double click, close, load, resize, etc.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

'event handler code goes here

End Sub
Basic Controls
• VB.Net provides a huge variety of controls that help you to create rich user interface.

• The following table lists some of the commonly used controls −


Control Naming Rules and Conventions
• Control names must start with a letter
• Remaining characters may be letters, digits, or underscore
• 1st 3 lowercase letters indicate the type of control
– txt… for Text Boxes
– lbl… for Labels
– btn… for Buttons
• After that, capitalize the first letter of each word
– txtHoursWorked is clearer than txthoursworked

The following slides explain how to use common controls…………..


Label Control

• Microsoft Visual Studio .NET controls are the graphical tools you use to
build the user interface of a VB.Net program.

• Labels are one of the most frequently used Visual Basic control.

• A Label control lets you place descriptive text , where the text does not
need to be changed by the user.

• The Label class is defined in the System.Windows.Forms namespace.


Label Control

• Add a Label control to the form.

• Click Label in the Toolbox and drag it over the forms Designer and drop it
in the desired location.
Label Control

• If you want to change the display text of the Label, you have to set a new
text to the Text property of Label.

Label1.Text = "This is my first Label"

• You can load Image in Label control , if you want to load an Image in the
Label control you can code like this

Label1.Image = Image.FromFile("C:\testimage.jpg")
Label Control

• The following source code shows how to set some properties of the Label
through coding.
Button Control

• A Button is a control, which is an interactive component that enables users


to communicate with an application which we click and release to perform
some actions.

• The Button control represents a standard button that reacts to a Click event.
A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if
the button has focus.
Button Control

• When you want to change display text of the Button , you can change the
Text property of the button.

Button1.Text = "My first Button"

• Similarly if you want to load an Image to a Button control , you can code
like this.

Button1.Image = Image.FromFile("C:\testimage.jpg")
Textbox Control

• A TextBox control is used to display, or accept as input, a single line of text.

• VB.Net programmers make extensive use of the TextBox control to let the
user view or enter large amount of text.

• A text box object is used to display text on a form or to get user input while
a VB.Net program is running.

• In a text box, a user can type data or paste it into the control from the
clipboard.
Textbox Control

• For displaying a text in a TextBox control , you can code like this.

TextBox1.Text = “Babcock University“

• You can also collect the input value from a TextBox control to a variable
like this way.

Dim var As String

var = TextBox1.Text
Textbox Control Properties

• You can set TextBox properties through Property window or through


program

• The below code set a textbox width as 150 and height as 25 through source
code.

TextBox1.Width = 150

TextBox1.Height = 25
Textbox Control Properties
• Background Color and Foreground Color
• You can set Textbox background color and foreground color through
property window, also you can set it programmatically.
TextBox1.BackColor = Color.Red
TextBox1.ForeColor = Color.Gray
• TextBox BorderStyle
• You can set 3 different types of border style for textbox in vb.net, they are
None, FixedSingle and fixed3d.
TextBox1.BorderStyle = BorderStyle.FixedSingle
Textbox Control Properties
• VB.Net Textbox Maximum Length
• Maximum Length property sets the maximum number of characters or
words the user can input into the text box control. That means you can limit
the user input by this property.
TextBox1.MaxLength = 25
• How to ReadOnly Textbox
• when a program wants to prevent a user from changing the text that appears
in a text box, the program can set the controls Readonly property is to True.
TextBox1.ReadOnly = True
Textbox Control Properties
• Multiline TextBox in vb.net
• By default TextBox accept single line of characters , If you need to enter
more than one line in a TextBox control, you should change the Multiline
property is to True.
• TextBox1.Multiline = True
• Textbox passowrd character
• Sometimes you want a textbox to receive password from the user. In order
to keep the password confidential, you can set the PasswordChar property
of a textbox to a specific character.
TextBox1.PasswordChar = "*“
Textbox Control Properties
• The above code set the PasswordChar to * , so when the user enter
password then it display only * instead of typed characters.
• How to Newline in TextBox
• You can add new line in a textbox using two ways.
TextBox1.Text += "some text here" + “\r\n”
• Or
TextBox1.Text += "some text here" + Environment.NewLine
Textbox Control Properties
• How to retrieve integer values from textbox ?
• VB.Net String to Integer conversion
Dim i As Integer
i = Integer.Parse(TextBox1.Text)
• Parse method Converts the string rep conversion presentation of a number
to its integer equivalent.
• VB.Net String to Double
Dim dbl As Double
dbl = Double.Parse(TextBox1.Text)
Textbox Control Events
• TextBox Keydown event
• Keydown event occurs when a key is pressed while the control has focus.
• TextChanged Event
• TextChanged Event is raised if the Text property is changed by either
through program modification or user input.
ComboBox Control
•  The ComboBox control lets the user choose one of several choices.
• The user can type a value in the text field or click the button to display a
drop down list.
• In addition to display and selection functionality, the ComboBox also
provides features that enable you to efficiently add items to the ComboBox.
ComboBox Control
• Add item to combobox
ComboBox1.Items.Add("Sunday")
ComboBox1.Items.Add("Monday")
ComboBox1.Items.Add("Tuesday")
ComboBox Control
• How to set the selected item in a comboBox
• You can set which item should shown while it displaying in the form for
first time.
comboBox1.Items.Add("test1")
comboBox1.Items.Add("test2")
comboBox1.Items.Add("test3")
comboBox1.SelectedItem = "test3"
• or
ComboBox1.SelectedItem = ComboBox1.Items(1)
• or
comboBox1.SelectedIndex = comboBox1.FindStringExact("test3")
ComboBox Selected Item
• How to retrieve value from ComboBox
• If you want to retrieve the displayed item to a string variable , you can code
like this
Dim var As String
var = ComboBox1.Text
Or
Dim item = Me.comboBox1.GetItemText(Me.comboBox1.SelectedItem)
MessageBox.Show(item)
ComboBox Selected Item
• How to remove an item from ComboBox in VB.Net
• You can remove items from a combobox in two ways. You can remove item
at a the specified index or giving a specified item by name.
ComboBox1.Items.RemoveAt(1)
• The above code will remove the second item from the combobox.
ComboBox1.Items.Remove("Friday")
• The above code will remove the item "Friday" from the combobox.
ComboBox DropDown Style
• The DropDownStyle property specifies whether the list is always displayed
or whether the list is displayed in a drop down.
• The DropDownStyle property also specifies whether the text portion can be
edited.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDown
ComboBox DropDown Style
• The DropDownStyle property specifies whether the list is always displayed
or whether the list is displayed in a drop down.
• The DropDownStyle property also specifies whether the text portion can be
edited.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDown
The Development Process
of Wage Calculator Application
Step 1 of Developing an Application

• Clearly define what the program is to do


 Purpose: To calculate the user’s gross pay
 Input: Number of hours worked, hourly pay rate
 Process: Multiply number of hours worked by hourly pay rate (result
is the user’s gross pay)
 Output: Display a message indicating the user’s gross pay
Step 2 of Developing an Application

• Visualize the application running on the computer and


design its user interface
Step 3 of Developing an Application
• Determine the controls needed
Control Type Control Name Description
Form (Default) A small form that will serve as the window
onto which the other controls will be placed
Label (Default) Displays the message Number of Hours
Label (Default) Displays the message Hourly Pay Rate
Label (Default) Displays the message Gross Pay Earned
TextBox txtHoursWorked Allows the user to enter the number of hours
worked
TextBox txtPayRate Allows the user to enter the hourly pay rate
Label lblGrossPay Displays the gross pay, after the
btnCalcGrossPay button has been clicked
Button btnCalcGrossPay When clicked, multiplies the number of hours
worked by the hourly pay rate; stores the result
in a variable and displays it in the
lblGrossPay label
Button btnClose When clicked, terminates the application
Step 4 of Developing an Application
• Define the values of each control’s relevant properties
Control Type Control Name Text Property
Form (Default) "Wage Calculator"
Label (Default) "Number of Hours"
Label (Default) "Hourly Pay Rate"
Label (Default) "Gross Pay Earned"
Label lblGrossPay "$0.00"
TextBox txtHoursWorked ""
TextBox txtPayRate ""
Button btnCalcGrossPay "Calculate Gross Pay"
Button btnClose "Close"
Step 5 of Developing an Application
• Determine the event handlers and other code needed for
each control
Event Handler Name Description

btnCalcGrossPay_Click Multiplies the number of hours worked by


the hourly pay rate; these values are
retrieved from the txtHoursWorked and
txtPayRate TextBox controls and the
result of the multiplication is stored in the
lblGrossPay label’s Text property

btnClose_Click Terminates the application


Step 6 of Developing an Application
• Create a flowchart or pseudocode version of the code
– A flowchart is a diagram that graphically depicts the
flow of a method

– Pseudocode is a cross between human language and


a programming language
Store Number of Hours Worked × Hourly Pay Rate in the grossPay variable.
Store the value of the grossPay variable in the lblGrossPay control’s Text property.
Step 7 of Developing an Application
• Check the flowchart or pseudocode for errors:
– Read the flowchart and/or pseudocode
– Step through each operation as though you are the computer
– Use a piece of paper to write down the values of variables and
properties as they change
– Verify that the expected results are achieved
Step 8 of Developing an Application
Now, let do step 8 to 11 together. Start your Visual Studio

• Start Visual Studio and create the forms and other controls identified in
Step 3
– This is the first use of Visual Studio
 All of the previous steps have just been on paper
– In this step you create the application’s user interface and arrange the
controls on each from.
 This is the portion of the application the user will see
Step 9 of Developing an Application
• Use the flowcharts or pseudocode from step 6 to write the actual code
– This is the second step on the computer
• In this step you develop the methods behind the click event for each
button
– Unlike the form developed on step 8, this portion of the application is
invisible to the user
Step 10 of Developing an Application
• Attempt to run the application - find syntax errors
– Correct any syntax errors found
– Syntax errors are the incorrect use of an element of the programming
language
– Repeat this step as many times as needed
– All syntax errors must be removed before the program will run
Step 11 of Developing an Application
• Run the application using test data as input
– Run the program with a variety of test data
– Check the results to be sure that they are correct
– Incorrect results are referred to as a runtime error
• Correct any runtime errors found
• Repeat this step as many times as necessary
Thank you

You might also like