SlideShare une entreprise Scribd logo
1  sur  131
VB.NET

                      ITCS 212
 Object Oriented Programming I
           By: Mrs. Marie Tupaz
What is Program, Programming and Basic Procedures

INTRO TO PROGRAMMING
What is Programming?

   • Program
     • a set of directions for the computer to
       complete a task

     • a sequence of instructions written to
       perform a specified task with a computer
What is Programming?

   Programming
   • process of designing,
     writing, testing, debugging, and
     maintaining the source
     code of computer programs
                                  • Wikipedia

   • giving the computer directions for
     completing a task
A computer is essentially a trained
 squirrel: acting on reflex,
 thoughtlessly running
Back and forth and storing away nuts
 until some other stimulus makes it
 do something else.
                         Ted Nelson
What is Programming

   • Example :

     • Baking a Cake
     • Making an Leche Plan
What is Programming?

   • Basic Task
                   Input



                  Process



                  Output
What is Programming?

   • Input – Key in data in computer
   • Process – the task given or work of the
     program
   • Output – the results

   Every Data must be declared before you
    can use and its called Declaration
What is programming?

   Baking a Cake:

   • Declarations : the measuring cups, the measuring
     spoons, the mixing bowl, and the cake pan. You must
     make sure you have these before you start.

   • Input : the ingredients, the cake mix, the eggs, the water,
     and such.

   • processing: the mixing and the baking – all the steps
     needed to turn your ingredients into a cake.

   • Output : the cake.
Basic Programming Procedure

   3 Category
   • Sequence - order of commands in a program
     (Washing dishes)
   • Selection - enable the computer to make
     decisions : Depending on decision, a different set of
     directions must be followed (laundry)
   • Repetition - allow the computer to repeat the
     same series of steps (Brushing teeth)
Basic Programming Procedure

   • Program Errors
    provide computer with precise directions for
    the task and provide these directions in a
    language the computer will understand

    If directions are wrong then the computer
    makes “mistakes.”

    How to minimize this mistakes?
Basic Programming Procedure

   • Algorithm
     • What is Algorithm?
       • is a step-by-step procedure

       • Lit. the description of the steps to solve the
         problem
Basic Programming Procedure

          Interface/Instruction
                    =
       Human/ Computer connection
Basic Programming Procedure

    Developer/User
   • Developer - is the person that develops
     the specifications, designs the program,
     creates the algorithm, writes the code,
     and tests the program
   • User: is the person that uses the
     finished program.
     • User part in program
        designing the program, and testing it
Basic Programming Procedure

   Design Time/Runtime

   • Design Time - when the program is
     developed, the interface is created, and
     the code is written
   • Run Time - program is running
Remember
    At design time a developer
 decides everything that a program
 will be and can do.
    At runtime, the program executes
 the commands given to it at design
 time.
Basic Programming Procedure

   Form/Code

   • Form window - often called the
     interface and is what the user sees
     when the program runs
   • Code window – where the directions
     the program is written and must never
     sees by the user
Basic Programming Procedure

   • Objects/Events

   • Objects – controls
   • Events – the ways a user interacts with
     the computer
Basic Programming Procedure

   Code Files/Program

   • To create or modify a program, you
     need the project folder and its files.
     These are used to create the
     executable file or .exe -- Finished
     program found in bin folder

     • .exe –, standalone program that can run
       even without VS
Short Quiz

QUIZ #2
ITCS 212

VISUAL BASIC IDE
Visual Basic.NET
    • Easier to Use
    • Streamlined and Modernized
    • More Powerful than VB 6.0
    • Higher level of access to system
      resources that in the past required
      the use of languages like C++
    • True Object Inheritance
    • Garbage Collection for better
      memory management
Visual Studio .NET 2003

    • Released April 27, 2003
    • J#
    • Mobile Web Applications: using the
      integrated ASP.NET Web Forms and
      the Visual Studio .NET Web Forms
      Designer, Visual Basic and C#
      developers can easily build thin-
      client Web-based applications that
      render intelligently on more than 200
      devices, including wireless
      application protocol (WAP) phones,
      wireless personal digital assistants
      (PDAs), and pagers.
New Web Development
   • Programming for the Web vs.
     Windows
   • New set of controls
   •   Web page layout
   •   ASP.NET
   •   ADO.NET
   •   Mobile Applications
   • Convert Projects
Just an Upgrade???
   • NO!
   • VB.NET omits quite a few forms of
     syntax
   • VB.NET requires a total rewrite rather
     than a simple port of code
   • VB.NET is not dependent on older
     libraries such as VBA runtime and
     ADO (ActiveX Database Object)
Forms are now Classes

   • In VB6, forms were
     classes, but you
     rarely treated them
     that way
   • VB .NET shows the
     code that instantiates
     the form
   • To show additional
     forms, you must first
     instantiate them
Form Changes

  • Forms have undergone a number
    of changes. These include:
    • The Forms engine is now
      WinForms and add such features
      as docking and opacity
    • Forms are classes
    • A Component Tray holds non-
      visual controls at design-time
VB.NET or C#.NET
    • C# is a new language that
      was designed to be
      friendly to programmers
      who are already
      proficient in C or C++
    • Either language can be
      used to write software
      that takes full advantage
      of the CLR and .NET
      framework
NEW IDE
New Tools

   •   Calendar Tool
   •   Date Picker Calendar
   •   Opacity Control
   •   Timer does not lay on form
   •   Command Buttons are now called
       Buttons
       • Use ―btn‖ for prefix
Great New Menu Tool
More Changes

   • The Editor window (formerly the
     Code window)
     • Lots more IntelliSense help;
        can be confusing
     • Declarations section replaces
         General Declarations
     • Collapsible Regions in code
        (Plus signs)
Collapsed Regions
              Tabs
                       Method List


   Class
     List




Collapsed
  Region

Collapsed
Procedure
General Changes
   • There have been a number of changes in
     VB .NET. General changes include:
     •   Form changes
     •   Option Strict
     •   Event Handler changes
     •   Default Properties
     •   Calling Subs and Functions
     •   Boolean operators
     •   Using CTRL + Space to finish variables
The Component Tray

   • In VB6, controls that were only
     visible at design-time still appeared
     on the form in the IDE
     • Such as the Timer control
   • VS .NET places controls that are
     invisible at runtime in a small area
     below the form
     • This area is the Component Tray
Forms are now Classes

   • In VB6, forms were classes, but you
     rarely treated them that way
   • VB .NET shows the code that
     instantiates the form
   • To show additional forms, you must
     first instantiate them
The Component Tray

   • In VB6, controls that were only
     visible at design-time still appeared
     on the form in the IDE
     • Such as the Timer control
   • VS .NET places controls that are
     invisible at runtime in a small area
     below the form
     • This area is the Component Tray
Calls to Subs and Functions
Require Parentheses
   • In VB6, you called a Sub without
     parentheses
     AddOrder OrderNum, OrderDate
   • You could use the Call statement, which
     required parenthese
     Call AddOrder(OrderNum, OrderDate)
   • .NET always requires parentheses for a
     Sub, as well as with Functions
New Boolean Operators

   • The And and Or keywords do not short-
     circuit in VB and VB .NET
     • Both sides of an operator are evaluated, even
       if the first option invalidates the statement
   • VB .NET adds two short-circuiting
     Boolean operators:
     • AndAlso
     • OrElse
Boolean Operators Example

     Dim x As Integer
     x = 0
     If x>2 And 5x > 1 Then ...
   • This If statement is already false on
     the x>2 part, but 5x is still checked
     because And does not short-circuit
   • In this case, 5x causes a ―divide by
     zero‖ error
Boolean Operators Example cont.

     Dim x As Integer
     x = 0
     If x>2 AndAlso 5x > 1 Then ...
   • This If statement is already false on
     the x>2 part, so the AndAlso does
     not check the 5x portion
   • The key result: No Error!
The Value of True

   • The value of True has not changed
     • Originally, the value of True was going
       to change, but it did not
   • The value of True in VB .NET is still
     negative one (-1)
   • Your code should not check for -1,
     but for True
Common Language Runtime

   • VB.NET has undergone a significant
     overhaul to accommodate the CLR
     • New object oriented design features
     • Much higher levels of type safety
     • Universal type system allows for greater
       inoperability
Changes in Properties

   • The Alignment property becomes
     TextAlign
   • The maximum length of identifiers is
     16,383
   • All new Help — MSDN
   • OptionButton becomes RadioButton
   • Frame becomes GroupBox
   • New component tray holds non-visible
     controls
More Property Changes
    • Text boxes have a Clear method
          txtName.Clear()
          txtName.Text = ―‖
    • Focus method replaces SetFocus
          txtName.Focus()
    • Many colors available through the Color
      class
       • lblMessage.ForeColor = Color.Blue
          Color.Aquamarine
          Color.Bisque
          Color.Chocolate
          Color.Cadetblue
Tab Order
    This is neat! Click on View and Tab
                     Order
Caption / Text Property
    • VB 6.0 - Some controls, such as
      Label, have a Caption property that
      determines the text displayed in or
      next to the control. Other
      controls, such as TextBox, have a
      Text property that determines the text
      contained in the control
    • VB.NET - In Windows Forms, the
      property that displays text in a
      control is consistently called Text on
      all controls. This simplifies the use of
      controls.
VB.NET IDE

   • Form Window
     • form window default name is Form1
     • Here you add controls to create the user
       interface.
   • Toolbox
     • contains the controls used to build the
       user interface
VB.NET IDE

   • Solution Explorer
     • contains a list of files and forms in your
       project
   • Properties Window
     • list of properties for each control.
     • The column on the left contains the
       names of the properties for that control.
     • The column on the right contains the
       settings for the properties.
VB.Net IDE
   • Naming Controls
     • Controls are identified by their names
     • Rules for naming controls
       • Names must start with a letter.
       • name can contain any combination of
         letters, numbers, or underscores ( ).
       • Name Cannot contain spaces.
       • Avoid using any special characters.
       • Names can be more than 1,000characters
         but limit it with twenty characters.
       • start all controls with a three-character
         prefix to identify the type of control
VB.Net IDE – Naming Controls
VB.Net IDE

   • Code Window
     • Where the program code is written
     • To view right click on the form and
       select View Code object the popup or
       double-click on the object
     • Example
       • Double-click on the Button
          • That opens the Code Window and creates a
            procedure and will create event
VB.Net IDE

   • Code Window
     • procedure is a block of code that
       completes a particular task.
       Private Sub
       …
       End Sub.
   • Event
     • When you double-clicked on the Button,
       it created a click event for that Button
Use and Parsing

DATA TYPES
Data Types

  byte     1 byte Range              Unsigned
                  0 to 255           byte
  sbyte    1 byte Range              Signed
                  -128 to 127        byte
  Short    2       Range             Signed
  (sho)    bytes   -32768 to 32767   short
  ushort   2       Range             Unsigned
           bytes   0 to 65535        short
More Integer Data Types
  int     4 bytes Range                Signed
                  -2,147,483,647 to
  (int)           2,147,483,647        integer
  uint    4 bytes Range                Unsigned
                  0 to 4,294,967,295
                                       integer
  long    8 bytes Greater than      Signed
  (lng)            900,000 trillion long int
  ulong 8 bytes Greater than 18        Unsigned
                million trillion       long int
Other Data Types
single       4     Range                     Float
(sng)        bytes A number 6 digits past    number
                     the decimal
double       8     Range                     Double
(dbl)        bytes A number 14 digits past   precision
                     the decimal
decimal      8     Range                     Fixed
             bytes A number 28 zeros long    precision

string (str) N/A   Range N/A                 Unicode
char         2     Range                     Unicode
             bytes 0x0000 to 0xFFFF          character

Bool (bln)         True or False             Boolean
Data types
Data types
Converting Data Types
    • Initialize a variable at declaration
           Dim intMax As Integer = 100I
           Dim decRate As Decimal = 0.08D
    • Declare multiple variables at once
           Dim intCount, intNum As Integer
    • Convert all input to correct data type
           (Do not use Val function)
           decSale = CDec(txtSale.Text)
           • CInt (still rounds to even #)
           • CDec
           • CStr
       ** CInt and CDec parse some characters
         like $, commas,()
Format

   • VB 6.0 –
     Format(variable, ―Currency‖)
   • VB.NET – FormatCurrency(variable)
     FormatPercent(variable)
     FormatNumber(variable)
     FormatNumber(variable,3)
     FormatDateTime(variable)
Changes in Syntax
    • Currency
      • Replaced with Decimal in VB.NET
    • The Currency data type (64 bit) does not
      provide sufficient accuracy to avoid
      rounding errors, so Decimal (96 bit) was
      created as its own data type.
      • Dim x As Currency
         is upgraded to:
         Dim x As Decimal
Long and Integer Data Types

   • VB 6.0 - Long variables were stored
     as 32-bit numbers and Integer
     variables as 16-bit numbers
   • VB.NET - Long variables are stored
     as 64-bit numbers, Integer variables
     are stored as 32-bit numbers, and
     Short variables are stored as 16-bit
     numbers.
Variant Data Type
    • From Variant data types to Object
      • due to keeping all the languages more similar.
        This is no longer the same as a pointer to an
        object.

    • Dim x As Variant

     is upgraded to:

     Dim x As Object
Object Data types

   • Object supports all classes in the .NET
     Framework class hierarchy and
     provides low-level services to derived
     classes. It is the root of the type
     hierarchy.
     • Everything inherits from Object-everything.
   • The Object data types make VB.NET
     better but they also make your
     programming easier.
Object Data types

   • 7 methods of Object:
     • Equals(Object) as Boolean
     • Equals(Object, Object) as Boolean
     • GetHashCode() as Integer
     • GetType() as System.Type
     • New()
     • ReferenceEquals(Object, Object) as
       Boolean
     • ToString() as String
Object Data types

   • If you look at another data type such as
     Char in the VB.NET Object Browser,
     you'll see six of the seven methods are
     also available.
   • The missing one is the constructor
     method, New(). This is taken care of
     when a variable is declared.
Object Data types

   • VB 6.0
     • If (UCase(chrl) >= "A" And UCase(chrl)
       <= "Z") Then ...
       • to find out if a one character string is actually a
         letter.
   • VB.NET,
     • If Char.IsLetter(myCharVar) Then ...
Option Explicit

    • Option Explicit { On | Off }

    • In VB.NET the option is turned on by
      default for all new projects.
    • When Option Explicit Off is used (not
      a good programming style), you can
      use any variable without first
      declaring it.
• To Set
  1. On the Tools menu, choose Options.
  2. Open the Projects and Solutions node.
  3. Choose VB Defaults.
  4. Modify the Option Explicit setting.
  5. To set Option Explicit on the command
     line
  6. Include the /optionexplicit compiler option
     in the vbc command.
• Example
• In this example Option
  Explicit statement use to force explicit
  declaration of all variables. Attempting
  to use an undeclared variable causes
  an error at compile time.
Force explicit variable declaration.

    • Option Explicit On

    • Dim thisVar As Integer thisVar = 10
      thisInt = 10 ' causes ERROR
Option Strict On
     • New Option in VB.NET
     • When Option Strict is turned on, the
       compiler/editor does not allow implicit
       conversions from a wider data type to a
       narrower one, or between String and
       numeric data types
     • When you use the Option Strict statement,
       the statement must appear before any other
       code
Option Strict On
     • Option Strict also generates an error
       message in the following scenarios:
       • For any undeclared variable. This is
         because Option Strict also implies Option
         Explicit.
       • Late binding.


     • If Option Strict is Off we can convert the
       value of Long to an Integer.
     • Limits erroneous numbers or run-time
       errors
Option Strict On
     • Example
       • Option Strict On
         Public Class Form1

         Private Sub Button1_Click(ByVal sender As
         System.Object, _ ByVal e As
         System.EventArgs) Handles Button1.Click

               Dim longNum As Long Dim intNum As
               Integer longNum = 12345 intNum =
               longNum MsgBox(intNum)
         End Sub
       End Class
Case Conversions

    • String ToUpper and ToLower methods
    • Replace UCase and LCase functions
    • If txtInput.Text.ToUpper = ―YES‖
New Compound Operators

   • New assignment Operators
   • += –= *= /= = &=
   • decTotal += decSale same as
     decTotal=decTotal + decSale
VARIABLES AND CONSTANTS
Creating variables

   • Variable
     • a storage container for your data
     • Declaration –creation of variable or
       declaring a variable
     • Assignment – change the value in a
       variable
     • Syntax
       • Dim varName As Type
     • Declaration Example
       • Dim shoTest as Short
Creating variables

   • Variable
     • initializing a variable
       • You must initialize a variable at the same
         time you declare it
       • Example
          • Dim shoCaseSize As Short = 24
          • Dim strLastName As String = "Jefferson―


   Remember : When you assign a value
    to a variable, you must make sure it
    can store the answer
Creating variables

   • Different assignment of variable
     • Use an assignment statement to place a
       value in a variable
       • shoTestScore = 88
     • assigning the value of one variable to
       another
       • strNewAddress = strOldAddress
     • using a mathematical equation
       • shoTotal = shoNum1 + shoNum2
       • shoTotal = shoNum1 + 10
Mathematical Operations
Rules of Precedence

   • what’s in parentheses first and work
     your way out,
   • exponentiation before other
     mathematical calculations,
   • multiplication and division from left
     to right, and then
   • addition and subtraction from left to
     right.
Rules of Precedence

   • Example
     • sngAverage = (shoTest1 + shoTest2 +
       shoTest3 + shoTest4)/4
     • 175=3
     • 17 Mod 5 = 2
     • 17^5
Creating Constants

   • Constants are like variables except
     their values cannot be changed while
     the program is running
     • Example
       • Const sngSalesTaxRate As Single = 0.05
       • Const strTitle As String = "A Tale of Two
         Cities"
Creating Constants

   • What is wrong with each of the
     following?
     •   shoNum + shoNum2 = shoTotal
     •   shoNum = 10∗4
     •   Dim decPrice As Decimal = "$4.99"
     •   shoCube = (shoSide)3
LOOP AND CONTROL
CONSTRUCT
Block-Level Scope

   • VB .NET introduces variables that
     only exist within blocks of code
     • Blocks are items such as
       For…Next, Do…Loop, and If Then…End
       If
   • Variables are only visible within the
     block, but their lifetime is that of the
     whole procedure
Block-Level Scope

   • For Loop
   • enable us to execute a series
     of expressions multiple numbers of
     times. For loop needs a loop
     index which counts the number of loop
     iterations as the loop executes.
For loop

   • syntax
     • For index=start to end[Step step]
       [statements]
       [Exit For]
       [statements]
       Next[index]
   • Example
       Dim i As Integer
       For i = 1 To 10
       Console.WriteLine(i)
       Next
Do.. Until

    • Do...UNTIL Loop
      • is a loop that runs until the loop's condition
        is true, the condition being checked after
        each iteration of the loop.
      • Syntax
         • Do
           statements
           Loop Until condition
Do.. Until

    • Example
      Do Until i > 10
                Console.WriteLine(i)
                i=i+1
            Loop
Do...Loop While

   • Do… While loop:

    A Do...Loop While loop runs until the
    loop's condition becomes false. Its
    condition is checked after each iteration
    of the loop.
Do...Loop While

   • Syntax
     • Do
       statements
       Loop While condition
   • Example Shows the DO while Loop:
         Do
           Console.WriteLine(i)
           i=i+1
         Loop While i < 10
OVERVIEW ARRAYS
Arrays
     • VB 6.0 - Arrays can be defined with lower
       and upper bounds of any whole number.
       The Option Base statement is used to
       determine the default lower bound if a
       range is not specified in the declaration.
     • VB.NET- To enable interoperability with
       other languages, all arrays must have a
       lower bound of zero. This makes the
       Option Base statement no longer
       necessary.
     • Dim a(1 To 10) As String
         is upgraded to:
       Dim a(10) As String
Array Size

   • This is one area that was going to
     change, but did not
     • When you declare an array, it starts at
       zero, and the element number you use
       is the Upper Bound of the array
     • This means that arrays will always be
       one larger than the size declared
     • Dim x(2) As Integer has three
       elements
While Loops
     • VB 6.0 - While statements are ended with
      a WEND statement.
     • VB.NET - WEND statements are changed
      to End While. This improves language
      consistency and readability.
       • It executes a block of statement as long as
         condition is true.
While Loops

   • syntax:
     • While condition
       statement-block
       End While
   • Example
     While i < 10
         Console.WriteLine(i)
          i = i + 1 // same with i+=1 or i++
      End While
Arrays Continued

   • Arrays in VB.NET are classes
     supporting properties and methods,
     making them quite flexible.
     • .Sort
     • .Reverse
   • You can sort an array in one line of
     code!
VB 6.0 to VB.net

OTHER CHANGES
Parameter Passing
    • VB 6.0 - Parameters that do not
      specify either ByVal or ByRef default
      to ByRef
    • VB.NET - Parameters that do not
      specify either ByVal or ByRef default
      to ByVal. Defaulting to ByVal rather
      than ByRef eliminates the problem of
      having a procedure mistakenly
      modify a variable passed in by the
      caller.
GoSub, On Goto

   • VB 6.0 - The GoSub line ... Return
     statement branches to and returns
     from a subroutine within a
     procedure.
   • VB.NET - GoSub...Return is a
     nonstructured programming
     construct. Its use makes programs
     harder to read and understand.
     Creating separate procedures that
     you can call may provide a more
     structured alternative or use case
     statements.
Structures Replace UDTs

   • User Defined Types (UDTs) have
     been replaced with Structures
   • Structures are far more powerful
     than UDTs
     • They support the equivalent of
       properties and methods
     • They are not as powerful as classes
File I/O Changes

   • VB .NET supports such built-in
     functions as FileOpen and Write
     • These functions are found in the
       Microsoft.VisualBasic namespace
   • VB6 code that is upgraded to VB
     .NET will use these functions
   • The Framework includes a rich
     namespace called System.IO
The System.IO Namespace

   • System.IO contains a large number
     of classes for handling all types of
     I/O
   • There are a variety of major
     categories of objects in System.IO
     • These include objects to manage files
       and directories, read and write text
       files, and read and write binary streams
Working with Files

   • FileInfo and DirectoryInfo
     classes are for such operations as
     creating, moving, and deleting files
     and directories
   • If you use the Open method of
     FileInfo to open a file, the returned
     object is a FileStream
Reading and Writing Files

   • The StreamReader and
     StreamWriter classes are common
     ways to perform file I/O
     • This can read binary and text data
   • The StringReader and StringWriter
     are designed to read text data
Structured Error Handling

   • VB .NET now supports Structured
     Exception Handling (SEH)
     • On Error Goto is still supported
   • SEH uses the Try…Catch…Finally
     syntax
   • Should help reduce spaghetti code
Overloading

   • Overloading is the ability to have the
     same method, but with different
     arguments
     • You could fake this in VB6 using
       ParamArrays
   • For example, a FindCustomer
     method could accept a customer ID,
     a customer name, or a contact name
Constructors and Destructors

   • Constructors are blocks of code that
     run when a class is instantiated
   • Destructors are blocks of code that
     run when a class drops out of
     memory
   • Constructors can be overloaded to
     make them more powerful
   • Due to garbage collection, you
     cannot be assured of when
     destructors will execute
Dispose and Finalize

   • Finalize will run when the object is
     cleaned up by the GC
   • You might want to release resources
     explicitly, since you cannot
     determine when Finalize will be
     called
   • Use the Dispose design pattern to
     explicitly free resources
Multithreading

   • VB .NET allows you to create truly
     multithreaded (or free threaded)
     applications
   • The Framework includes a
     System.Threading namespace to
     make working with threads easier
   • You will learn more in Chapter 11,
     ―Multithreaded Applications‖
Windows VB.NET Example
Activity #1

TUITION CALCULATOR
Activity # 1 - Tuition Calculator
Activity # 1 - Tuition Calculator
   • TuitionCalculator Code
     •   Public Class frmTuitionCalculator
     •   Private Sub btnExit_Click(ByVal sender As System.Object,
     •   ByVal e As System.EventArgs) Handles btnExit.Click
     •   End
     •   End Sub
     •   Private Sub btnTuition_Click(ByVal sender As
     •   System.Object, ByVal e As System.EventArgs) Handles
     •   btnTuition.Click
     •   Dim shoCredits As Short
     •   Dim decTuition As Decimal
     •   shoCredits = txtCredits.Text
     •   decTuition = shoCredits * 100
     •   lblTuition.Text = decTuition.ToString
     •   End Sub
     •   End Class
Keywords and Terms
Keywords and Terms
Keywords and Terms
Keywords and Terms
Keywords and Terms
Quiz # 3

LONG QUIZ
COMMON PROGRAMMING
ERRORS
Errors in Your Program
   • Syntax errors
     spelling or usage errors in your code.
     Computer doesn’t understand what
      you’ve written.
   • Logical errors
     • errors in your thinking. The computer
       understands the commands, but the
       ―what to do‖ or ― how to do them‖ is
       different than what you were expecting.
   • Runtime errors
     • Problems that crash a program.
Creating Vb. Simple program

VB.NET AT WORK
Activity # 1 - Tuition Calculator
Activity # 1 - Tuition Calculator

    • Procedure for creating the program
    • Form Window
      1. In every System you must first to create the
         user interface and add all the control needed
      2. name all the controls
      3. Choose the control that will trigger the event
         and go to code window


      Note: Design should follow later after the
        program works
Activity # 1 - Tuition Calculator

    • Procedure for creating the program
    • Code Window
Activity # 1 - Tuition Calculator
   • TuitionCalculator Code
     •   Public Class frmTuitionCalculator
     •   Private Sub btnExit_Click(ByVal sender As System.Object,
     •   ByVal e As System.EventArgs) Handles btnExit.Click
     •   End
     •   End Sub
     •   Private Sub btnTuition_Click(ByVal sender As
     •   System.Object, ByVal e As System.EventArgs) Handles
     •   btnTuition.Click
     •   Dim shoCredits As Short
     •   Dim decTuition As Decimal
     •   shoCredits = txtCredits.Text
     •   decTuition = shoCredits * 100
     •   lblTuition.Text = decTuition.ToString
     •   End Sub
     •   End Class
Object Oriented Programming I

Contenu connexe

En vedette

Melvin Cureton Portfolio Vb.Net Windows 1
Melvin Cureton Portfolio Vb.Net Windows 1Melvin Cureton Portfolio Vb.Net Windows 1
Melvin Cureton Portfolio Vb.Net Windows 1
Melvin Cureton
 

En vedette (20)

Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Melvin Cureton Portfolio Vb.Net Windows 1
Melvin Cureton Portfolio Vb.Net Windows 1Melvin Cureton Portfolio Vb.Net Windows 1
Melvin Cureton Portfolio Vb.Net Windows 1
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Visual studio 2012 - What's in it for me?
Visual studio 2012 - What's in it for me?Visual studio 2012 - What's in it for me?
Visual studio 2012 - What's in it for me?
 
Manual visual basic .net
Manual visual basic .net Manual visual basic .net
Manual visual basic .net
 
Principios de diseño oo
Principios de diseño ooPrincipios de diseño oo
Principios de diseño oo
 
New SharePoint Features in Visual Studio 2012!
New SharePoint Features in Visual Studio 2012!New SharePoint Features in Visual Studio 2012!
New SharePoint Features in Visual Studio 2012!
 
Capa negocio con clases en VB
Capa negocio con clases en VBCapa negocio con clases en VB
Capa negocio con clases en VB
 
Moving to Microsoft Visual Basic .NET
Moving to Microsoft Visual Basic .NETMoving to Microsoft Visual Basic .NET
Moving to Microsoft Visual Basic .NET
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
 
Visual Basic IDE Introduction
Visual Basic IDE IntroductionVisual Basic IDE Introduction
Visual Basic IDE Introduction
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
Visual Studio 2012 introduction
Visual Studio  2012 introductionVisual Studio  2012 introduction
Visual Studio 2012 introduction
 
Developing SharePoint 2013 apps with Visual Studio 2012 - SharePoint Connecti...
Developing SharePoint 2013 apps with Visual Studio 2012 - SharePoint Connecti...Developing SharePoint 2013 apps with Visual Studio 2012 - SharePoint Connecti...
Developing SharePoint 2013 apps with Visual Studio 2012 - SharePoint Connecti...
 
Learning VB.NET Programming Concepts
Learning VB.NET Programming ConceptsLearning VB.NET Programming Concepts
Learning VB.NET Programming Concepts
 
Modelos de desarrollo de aplicaciones web
Modelos de desarrollo de aplicaciones webModelos de desarrollo de aplicaciones web
Modelos de desarrollo de aplicaciones web
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Create Contacts program with VB.Net
Create Contacts program with VB.NetCreate Contacts program with VB.Net
Create Contacts program with VB.Net
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
 
Introduction to Visual studio 2012
Introduction to Visual studio 2012 Introduction to Visual studio 2012
Introduction to Visual studio 2012
 

Similaire à Object Oriented Programming I

NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
Dmytro Mindra
 
August Webinar - Water Cooler Talks: A Look into a Developer's Workbench
August Webinar - Water Cooler Talks: A Look into a Developer's WorkbenchAugust Webinar - Water Cooler Talks: A Look into a Developer's Workbench
August Webinar - Water Cooler Talks: A Look into a Developer's Workbench
Howard Greenberg
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement online
Garuda Trainings
 

Similaire à Object Oriented Programming I (20)

10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming
 
Introduction_to_NET.ppt
Introduction_to_NET.pptIntroduction_to_NET.ppt
Introduction_to_NET.ppt
 
Vba Class Level 3
Vba Class Level 3Vba Class Level 3
Vba Class Level 3
 
Staging and Deployment
Staging and DeploymentStaging and Deployment
Staging and Deployment
 
Build, Test and Extend Integrated Workflows 3.7
Build, Test and Extend Integrated Workflows 3.7Build, Test and Extend Integrated Workflows 3.7
Build, Test and Extend Integrated Workflows 3.7
 
NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
 
C#: Past, Present and Future
C#: Past, Present and FutureC#: Past, Present and Future
C#: Past, Present and Future
 
August Webinar - Water Cooler Talks: A Look into a Developer's Workbench
August Webinar - Water Cooler Talks: A Look into a Developer's WorkbenchAugust Webinar - Water Cooler Talks: A Look into a Developer's Workbench
August Webinar - Water Cooler Talks: A Look into a Developer's Workbench
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement online
 
C og c++-jens lund jensen
C og c++-jens lund jensenC og c++-jens lund jensen
C og c++-jens lund jensen
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting example
 
Building environment of #UserDevOps and not only DevOps
Building environment of #UserDevOps and not only DevOpsBuilding environment of #UserDevOps and not only DevOps
Building environment of #UserDevOps and not only DevOps
 
Bringing DevOps to the Database
Bringing DevOps to the DatabaseBringing DevOps to the Database
Bringing DevOps to the Database
 
Introducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsIntroducing systems analysis, design & development Concepts
Introducing systems analysis, design & development Concepts
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Is your ABAP Code Ready for the Cloud?
Is your ABAP Code Ready for the Cloud?Is your ABAP Code Ready for the Cloud?
Is your ABAP Code Ready for the Cloud?
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Alm with tfs 2013
Alm with tfs 2013Alm with tfs 2013
Alm with tfs 2013
 
Achieving Full Stack DevOps at Colonial Life
Achieving Full Stack DevOps at Colonial Life Achieving Full Stack DevOps at Colonial Life
Achieving Full Stack DevOps at Colonial Life
 

Dernier

Dernier (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Object Oriented Programming I

  • 1. VB.NET ITCS 212 Object Oriented Programming I By: Mrs. Marie Tupaz
  • 2. What is Program, Programming and Basic Procedures INTRO TO PROGRAMMING
  • 3. What is Programming? • Program • a set of directions for the computer to complete a task • a sequence of instructions written to perform a specified task with a computer
  • 4. What is Programming? Programming • process of designing, writing, testing, debugging, and maintaining the source code of computer programs • Wikipedia • giving the computer directions for completing a task
  • 5. A computer is essentially a trained squirrel: acting on reflex, thoughtlessly running Back and forth and storing away nuts until some other stimulus makes it do something else. Ted Nelson
  • 6. What is Programming • Example : • Baking a Cake • Making an Leche Plan
  • 7. What is Programming? • Basic Task Input Process Output
  • 8. What is Programming? • Input – Key in data in computer • Process – the task given or work of the program • Output – the results Every Data must be declared before you can use and its called Declaration
  • 9. What is programming? Baking a Cake: • Declarations : the measuring cups, the measuring spoons, the mixing bowl, and the cake pan. You must make sure you have these before you start. • Input : the ingredients, the cake mix, the eggs, the water, and such. • processing: the mixing and the baking – all the steps needed to turn your ingredients into a cake. • Output : the cake.
  • 10. Basic Programming Procedure 3 Category • Sequence - order of commands in a program (Washing dishes) • Selection - enable the computer to make decisions : Depending on decision, a different set of directions must be followed (laundry) • Repetition - allow the computer to repeat the same series of steps (Brushing teeth)
  • 11. Basic Programming Procedure • Program Errors provide computer with precise directions for the task and provide these directions in a language the computer will understand If directions are wrong then the computer makes “mistakes.” How to minimize this mistakes?
  • 12. Basic Programming Procedure • Algorithm • What is Algorithm? • is a step-by-step procedure • Lit. the description of the steps to solve the problem
  • 13. Basic Programming Procedure Interface/Instruction = Human/ Computer connection
  • 14. Basic Programming Procedure Developer/User • Developer - is the person that develops the specifications, designs the program, creates the algorithm, writes the code, and tests the program • User: is the person that uses the finished program. • User part in program designing the program, and testing it
  • 15. Basic Programming Procedure Design Time/Runtime • Design Time - when the program is developed, the interface is created, and the code is written • Run Time - program is running
  • 16. Remember At design time a developer decides everything that a program will be and can do. At runtime, the program executes the commands given to it at design time.
  • 17. Basic Programming Procedure Form/Code • Form window - often called the interface and is what the user sees when the program runs • Code window – where the directions the program is written and must never sees by the user
  • 18. Basic Programming Procedure • Objects/Events • Objects – controls • Events – the ways a user interacts with the computer
  • 19. Basic Programming Procedure Code Files/Program • To create or modify a program, you need the project folder and its files. These are used to create the executable file or .exe -- Finished program found in bin folder • .exe –, standalone program that can run even without VS
  • 22. Visual Basic.NET • Easier to Use • Streamlined and Modernized • More Powerful than VB 6.0 • Higher level of access to system resources that in the past required the use of languages like C++ • True Object Inheritance • Garbage Collection for better memory management
  • 23. Visual Studio .NET 2003 • Released April 27, 2003 • J# • Mobile Web Applications: using the integrated ASP.NET Web Forms and the Visual Studio .NET Web Forms Designer, Visual Basic and C# developers can easily build thin- client Web-based applications that render intelligently on more than 200 devices, including wireless application protocol (WAP) phones, wireless personal digital assistants (PDAs), and pagers.
  • 24. New Web Development • Programming for the Web vs. Windows • New set of controls • Web page layout • ASP.NET • ADO.NET • Mobile Applications • Convert Projects
  • 25. Just an Upgrade??? • NO! • VB.NET omits quite a few forms of syntax • VB.NET requires a total rewrite rather than a simple port of code • VB.NET is not dependent on older libraries such as VBA runtime and ADO (ActiveX Database Object)
  • 26. Forms are now Classes • In VB6, forms were classes, but you rarely treated them that way • VB .NET shows the code that instantiates the form • To show additional forms, you must first instantiate them
  • 27. Form Changes • Forms have undergone a number of changes. These include: • The Forms engine is now WinForms and add such features as docking and opacity • Forms are classes • A Component Tray holds non- visual controls at design-time
  • 28. VB.NET or C#.NET • C# is a new language that was designed to be friendly to programmers who are already proficient in C or C++ • Either language can be used to write software that takes full advantage of the CLR and .NET framework
  • 30. New Tools • Calendar Tool • Date Picker Calendar • Opacity Control • Timer does not lay on form • Command Buttons are now called Buttons • Use ―btn‖ for prefix
  • 32. More Changes • The Editor window (formerly the Code window) • Lots more IntelliSense help; can be confusing • Declarations section replaces General Declarations • Collapsible Regions in code (Plus signs)
  • 33. Collapsed Regions Tabs Method List Class List Collapsed Region Collapsed Procedure
  • 34. General Changes • There have been a number of changes in VB .NET. General changes include: • Form changes • Option Strict • Event Handler changes • Default Properties • Calling Subs and Functions • Boolean operators • Using CTRL + Space to finish variables
  • 35. The Component Tray • In VB6, controls that were only visible at design-time still appeared on the form in the IDE • Such as the Timer control • VS .NET places controls that are invisible at runtime in a small area below the form • This area is the Component Tray
  • 36. Forms are now Classes • In VB6, forms were classes, but you rarely treated them that way • VB .NET shows the code that instantiates the form • To show additional forms, you must first instantiate them
  • 37. The Component Tray • In VB6, controls that were only visible at design-time still appeared on the form in the IDE • Such as the Timer control • VS .NET places controls that are invisible at runtime in a small area below the form • This area is the Component Tray
  • 38. Calls to Subs and Functions Require Parentheses • In VB6, you called a Sub without parentheses AddOrder OrderNum, OrderDate • You could use the Call statement, which required parenthese Call AddOrder(OrderNum, OrderDate) • .NET always requires parentheses for a Sub, as well as with Functions
  • 39. New Boolean Operators • The And and Or keywords do not short- circuit in VB and VB .NET • Both sides of an operator are evaluated, even if the first option invalidates the statement • VB .NET adds two short-circuiting Boolean operators: • AndAlso • OrElse
  • 40. Boolean Operators Example Dim x As Integer x = 0 If x>2 And 5x > 1 Then ... • This If statement is already false on the x>2 part, but 5x is still checked because And does not short-circuit • In this case, 5x causes a ―divide by zero‖ error
  • 41. Boolean Operators Example cont. Dim x As Integer x = 0 If x>2 AndAlso 5x > 1 Then ... • This If statement is already false on the x>2 part, so the AndAlso does not check the 5x portion • The key result: No Error!
  • 42. The Value of True • The value of True has not changed • Originally, the value of True was going to change, but it did not • The value of True in VB .NET is still negative one (-1) • Your code should not check for -1, but for True
  • 43. Common Language Runtime • VB.NET has undergone a significant overhaul to accommodate the CLR • New object oriented design features • Much higher levels of type safety • Universal type system allows for greater inoperability
  • 44. Changes in Properties • The Alignment property becomes TextAlign • The maximum length of identifiers is 16,383 • All new Help — MSDN • OptionButton becomes RadioButton • Frame becomes GroupBox • New component tray holds non-visible controls
  • 45. More Property Changes • Text boxes have a Clear method txtName.Clear() txtName.Text = ―‖ • Focus method replaces SetFocus txtName.Focus() • Many colors available through the Color class • lblMessage.ForeColor = Color.Blue Color.Aquamarine Color.Bisque Color.Chocolate Color.Cadetblue
  • 46. Tab Order This is neat! Click on View and Tab Order
  • 47. Caption / Text Property • VB 6.0 - Some controls, such as Label, have a Caption property that determines the text displayed in or next to the control. Other controls, such as TextBox, have a Text property that determines the text contained in the control • VB.NET - In Windows Forms, the property that displays text in a control is consistently called Text on all controls. This simplifies the use of controls.
  • 48. VB.NET IDE • Form Window • form window default name is Form1 • Here you add controls to create the user interface. • Toolbox • contains the controls used to build the user interface
  • 49. VB.NET IDE • Solution Explorer • contains a list of files and forms in your project • Properties Window • list of properties for each control. • The column on the left contains the names of the properties for that control. • The column on the right contains the settings for the properties.
  • 50. VB.Net IDE • Naming Controls • Controls are identified by their names • Rules for naming controls • Names must start with a letter. • name can contain any combination of letters, numbers, or underscores ( ). • Name Cannot contain spaces. • Avoid using any special characters. • Names can be more than 1,000characters but limit it with twenty characters. • start all controls with a three-character prefix to identify the type of control
  • 51. VB.Net IDE – Naming Controls
  • 52. VB.Net IDE • Code Window • Where the program code is written • To view right click on the form and select View Code object the popup or double-click on the object • Example • Double-click on the Button • That opens the Code Window and creates a procedure and will create event
  • 53. VB.Net IDE • Code Window • procedure is a block of code that completes a particular task. Private Sub … End Sub. • Event • When you double-clicked on the Button, it created a click event for that Button
  • 55. Data Types byte 1 byte Range Unsigned 0 to 255 byte sbyte 1 byte Range Signed -128 to 127 byte Short 2 Range Signed (sho) bytes -32768 to 32767 short ushort 2 Range Unsigned bytes 0 to 65535 short
  • 56. More Integer Data Types int 4 bytes Range Signed -2,147,483,647 to (int) 2,147,483,647 integer uint 4 bytes Range Unsigned 0 to 4,294,967,295 integer long 8 bytes Greater than Signed (lng) 900,000 trillion long int ulong 8 bytes Greater than 18 Unsigned million trillion long int
  • 57. Other Data Types single 4 Range Float (sng) bytes A number 6 digits past number the decimal double 8 Range Double (dbl) bytes A number 14 digits past precision the decimal decimal 8 Range Fixed bytes A number 28 zeros long precision string (str) N/A Range N/A Unicode char 2 Range Unicode bytes 0x0000 to 0xFFFF character Bool (bln) True or False Boolean
  • 60. Converting Data Types • Initialize a variable at declaration Dim intMax As Integer = 100I Dim decRate As Decimal = 0.08D • Declare multiple variables at once Dim intCount, intNum As Integer • Convert all input to correct data type (Do not use Val function) decSale = CDec(txtSale.Text) • CInt (still rounds to even #) • CDec • CStr ** CInt and CDec parse some characters like $, commas,()
  • 61. Format • VB 6.0 – Format(variable, ―Currency‖) • VB.NET – FormatCurrency(variable) FormatPercent(variable) FormatNumber(variable) FormatNumber(variable,3) FormatDateTime(variable)
  • 62. Changes in Syntax • Currency • Replaced with Decimal in VB.NET • The Currency data type (64 bit) does not provide sufficient accuracy to avoid rounding errors, so Decimal (96 bit) was created as its own data type. • Dim x As Currency is upgraded to: Dim x As Decimal
  • 63. Long and Integer Data Types • VB 6.0 - Long variables were stored as 32-bit numbers and Integer variables as 16-bit numbers • VB.NET - Long variables are stored as 64-bit numbers, Integer variables are stored as 32-bit numbers, and Short variables are stored as 16-bit numbers.
  • 64. Variant Data Type • From Variant data types to Object • due to keeping all the languages more similar. This is no longer the same as a pointer to an object. • Dim x As Variant is upgraded to: Dim x As Object
  • 65. Object Data types • Object supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. It is the root of the type hierarchy. • Everything inherits from Object-everything. • The Object data types make VB.NET better but they also make your programming easier.
  • 66. Object Data types • 7 methods of Object: • Equals(Object) as Boolean • Equals(Object, Object) as Boolean • GetHashCode() as Integer • GetType() as System.Type • New() • ReferenceEquals(Object, Object) as Boolean • ToString() as String
  • 67. Object Data types • If you look at another data type such as Char in the VB.NET Object Browser, you'll see six of the seven methods are also available. • The missing one is the constructor method, New(). This is taken care of when a variable is declared.
  • 68. Object Data types • VB 6.0 • If (UCase(chrl) >= "A" And UCase(chrl) <= "Z") Then ... • to find out if a one character string is actually a letter. • VB.NET, • If Char.IsLetter(myCharVar) Then ...
  • 69. Option Explicit • Option Explicit { On | Off } • In VB.NET the option is turned on by default for all new projects. • When Option Explicit Off is used (not a good programming style), you can use any variable without first declaring it.
  • 70. • To Set 1. On the Tools menu, choose Options. 2. Open the Projects and Solutions node. 3. Choose VB Defaults. 4. Modify the Option Explicit setting. 5. To set Option Explicit on the command line 6. Include the /optionexplicit compiler option in the vbc command.
  • 71. • Example • In this example Option Explicit statement use to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time.
  • 72. Force explicit variable declaration. • Option Explicit On • Dim thisVar As Integer thisVar = 10 thisInt = 10 ' causes ERROR
  • 73. Option Strict On • New Option in VB.NET • When Option Strict is turned on, the compiler/editor does not allow implicit conversions from a wider data type to a narrower one, or between String and numeric data types • When you use the Option Strict statement, the statement must appear before any other code
  • 74. Option Strict On • Option Strict also generates an error message in the following scenarios: • For any undeclared variable. This is because Option Strict also implies Option Explicit. • Late binding. • If Option Strict is Off we can convert the value of Long to an Integer. • Limits erroneous numbers or run-time errors
  • 75. Option Strict On • Example • Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum MsgBox(intNum) End Sub End Class
  • 76. Case Conversions • String ToUpper and ToLower methods • Replace UCase and LCase functions • If txtInput.Text.ToUpper = ―YES‖
  • 77. New Compound Operators • New assignment Operators • += –= *= /= = &= • decTotal += decSale same as decTotal=decTotal + decSale
  • 79. Creating variables • Variable • a storage container for your data • Declaration –creation of variable or declaring a variable • Assignment – change the value in a variable • Syntax • Dim varName As Type • Declaration Example • Dim shoTest as Short
  • 80. Creating variables • Variable • initializing a variable • You must initialize a variable at the same time you declare it • Example • Dim shoCaseSize As Short = 24 • Dim strLastName As String = "Jefferson― Remember : When you assign a value to a variable, you must make sure it can store the answer
  • 81. Creating variables • Different assignment of variable • Use an assignment statement to place a value in a variable • shoTestScore = 88 • assigning the value of one variable to another • strNewAddress = strOldAddress • using a mathematical equation • shoTotal = shoNum1 + shoNum2 • shoTotal = shoNum1 + 10
  • 83. Rules of Precedence • what’s in parentheses first and work your way out, • exponentiation before other mathematical calculations, • multiplication and division from left to right, and then • addition and subtraction from left to right.
  • 84. Rules of Precedence • Example • sngAverage = (shoTest1 + shoTest2 + shoTest3 + shoTest4)/4 • 175=3 • 17 Mod 5 = 2 • 17^5
  • 85. Creating Constants • Constants are like variables except their values cannot be changed while the program is running • Example • Const sngSalesTaxRate As Single = 0.05 • Const strTitle As String = "A Tale of Two Cities"
  • 86. Creating Constants • What is wrong with each of the following? • shoNum + shoNum2 = shoTotal • shoNum = 10∗4 • Dim decPrice As Decimal = "$4.99" • shoCube = (shoSide)3
  • 88. Block-Level Scope • VB .NET introduces variables that only exist within blocks of code • Blocks are items such as For…Next, Do…Loop, and If Then…End If • Variables are only visible within the block, but their lifetime is that of the whole procedure
  • 89. Block-Level Scope • For Loop • enable us to execute a series of expressions multiple numbers of times. For loop needs a loop index which counts the number of loop iterations as the loop executes.
  • 90. For loop • syntax • For index=start to end[Step step] [statements] [Exit For] [statements] Next[index] • Example Dim i As Integer For i = 1 To 10 Console.WriteLine(i) Next
  • 91. Do.. Until • Do...UNTIL Loop • is a loop that runs until the loop's condition is true, the condition being checked after each iteration of the loop. • Syntax • Do statements Loop Until condition
  • 92. Do.. Until • Example Do Until i > 10 Console.WriteLine(i) i=i+1 Loop
  • 93. Do...Loop While • Do… While loop: A Do...Loop While loop runs until the loop's condition becomes false. Its condition is checked after each iteration of the loop.
  • 94. Do...Loop While • Syntax • Do statements Loop While condition • Example Shows the DO while Loop: Do Console.WriteLine(i) i=i+1 Loop While i < 10
  • 96. Arrays • VB 6.0 - Arrays can be defined with lower and upper bounds of any whole number. The Option Base statement is used to determine the default lower bound if a range is not specified in the declaration. • VB.NET- To enable interoperability with other languages, all arrays must have a lower bound of zero. This makes the Option Base statement no longer necessary. • Dim a(1 To 10) As String is upgraded to: Dim a(10) As String
  • 97. Array Size • This is one area that was going to change, but did not • When you declare an array, it starts at zero, and the element number you use is the Upper Bound of the array • This means that arrays will always be one larger than the size declared • Dim x(2) As Integer has three elements
  • 98. While Loops • VB 6.0 - While statements are ended with a WEND statement. • VB.NET - WEND statements are changed to End While. This improves language consistency and readability. • It executes a block of statement as long as condition is true.
  • 99. While Loops • syntax: • While condition statement-block End While • Example While i < 10 Console.WriteLine(i) i = i + 1 // same with i+=1 or i++ End While
  • 100. Arrays Continued • Arrays in VB.NET are classes supporting properties and methods, making them quite flexible. • .Sort • .Reverse • You can sort an array in one line of code!
  • 101. VB 6.0 to VB.net OTHER CHANGES
  • 102. Parameter Passing • VB 6.0 - Parameters that do not specify either ByVal or ByRef default to ByRef • VB.NET - Parameters that do not specify either ByVal or ByRef default to ByVal. Defaulting to ByVal rather than ByRef eliminates the problem of having a procedure mistakenly modify a variable passed in by the caller.
  • 103. GoSub, On Goto • VB 6.0 - The GoSub line ... Return statement branches to and returns from a subroutine within a procedure. • VB.NET - GoSub...Return is a nonstructured programming construct. Its use makes programs harder to read and understand. Creating separate procedures that you can call may provide a more structured alternative or use case statements.
  • 104. Structures Replace UDTs • User Defined Types (UDTs) have been replaced with Structures • Structures are far more powerful than UDTs • They support the equivalent of properties and methods • They are not as powerful as classes
  • 105. File I/O Changes • VB .NET supports such built-in functions as FileOpen and Write • These functions are found in the Microsoft.VisualBasic namespace • VB6 code that is upgraded to VB .NET will use these functions • The Framework includes a rich namespace called System.IO
  • 106. The System.IO Namespace • System.IO contains a large number of classes for handling all types of I/O • There are a variety of major categories of objects in System.IO • These include objects to manage files and directories, read and write text files, and read and write binary streams
  • 107. Working with Files • FileInfo and DirectoryInfo classes are for such operations as creating, moving, and deleting files and directories • If you use the Open method of FileInfo to open a file, the returned object is a FileStream
  • 108. Reading and Writing Files • The StreamReader and StreamWriter classes are common ways to perform file I/O • This can read binary and text data • The StringReader and StringWriter are designed to read text data
  • 109. Structured Error Handling • VB .NET now supports Structured Exception Handling (SEH) • On Error Goto is still supported • SEH uses the Try…Catch…Finally syntax • Should help reduce spaghetti code
  • 110. Overloading • Overloading is the ability to have the same method, but with different arguments • You could fake this in VB6 using ParamArrays • For example, a FindCustomer method could accept a customer ID, a customer name, or a contact name
  • 111. Constructors and Destructors • Constructors are blocks of code that run when a class is instantiated • Destructors are blocks of code that run when a class drops out of memory • Constructors can be overloaded to make them more powerful • Due to garbage collection, you cannot be assured of when destructors will execute
  • 112. Dispose and Finalize • Finalize will run when the object is cleaned up by the GC • You might want to release resources explicitly, since you cannot determine when Finalize will be called • Use the Dispose design pattern to explicitly free resources
  • 113. Multithreading • VB .NET allows you to create truly multithreaded (or free threaded) applications • The Framework includes a System.Threading namespace to make working with threads easier • You will learn more in Chapter 11, ―Multithreaded Applications‖
  • 116. Activity # 1 - Tuition Calculator
  • 117. Activity # 1 - Tuition Calculator • TuitionCalculator Code • Public Class frmTuitionCalculator • Private Sub btnExit_Click(ByVal sender As System.Object, • ByVal e As System.EventArgs) Handles btnExit.Click • End • End Sub • Private Sub btnTuition_Click(ByVal sender As • System.Object, ByVal e As System.EventArgs) Handles • btnTuition.Click • Dim shoCredits As Short • Dim decTuition As Decimal • shoCredits = txtCredits.Text • decTuition = shoCredits * 100 • lblTuition.Text = decTuition.ToString • End Sub • End Class
  • 123. Quiz # 3 LONG QUIZ
  • 125. Errors in Your Program • Syntax errors spelling or usage errors in your code. Computer doesn’t understand what you’ve written. • Logical errors • errors in your thinking. The computer understands the commands, but the ―what to do‖ or ― how to do them‖ is different than what you were expecting. • Runtime errors • Problems that crash a program.
  • 126. Creating Vb. Simple program VB.NET AT WORK
  • 127. Activity # 1 - Tuition Calculator
  • 128. Activity # 1 - Tuition Calculator • Procedure for creating the program • Form Window 1. In every System you must first to create the user interface and add all the control needed 2. name all the controls 3. Choose the control that will trigger the event and go to code window Note: Design should follow later after the program works
  • 129. Activity # 1 - Tuition Calculator • Procedure for creating the program • Code Window
  • 130. Activity # 1 - Tuition Calculator • TuitionCalculator Code • Public Class frmTuitionCalculator • Private Sub btnExit_Click(ByVal sender As System.Object, • ByVal e As System.EventArgs) Handles btnExit.Click • End • End Sub • Private Sub btnTuition_Click(ByVal sender As • System.Object, ByVal e As System.EventArgs) Handles • btnTuition.Click • Dim shoCredits As Short • Dim decTuition As Decimal • shoCredits = txtCredits.Text • decTuition = shoCredits * 100 • lblTuition.Text = decTuition.ToString • End Sub • End Class

Notes de l'éditeur

  1. The computer does exactly what you tell it to do, even when that’s notwhat you want it to do.That’s not a computer error; it’s probably a programmer’s error.The person writing the directions for the computer is the one that made themistake. It’s called “human error,” and at the heart of most computer problemsis a person. Whether we like to admit it, most of the time computer error ismerely human error in disguise.
  2. Declarations tell the computer what type of data you have for your program. Declarations almostalways come at the beginning of a task.
  3. These tasks enable the computer to handle all processing procedures that come along. Each one has a particular utility that makesthe computer function effectively.
  4. To minimize these mistakes, programmers need to learn the fundamentals for writing programs
  5. Withit,aprogrammerdecidesthesequenceofsteps,thedecisionsthat must be made, and the steps that need to be repeated
  6. At this stage, you’re both the developer and the user. You’ll design programsand use them, which offers some advantages and some disadvantages. You cansee both sides of the program. You’ll find out just how hard it is to design andcode a program that the average person can use, how much work is involved inprogramming, and how difficult it is to anticipate the needs of the user. But, onthe bright side, you can also design a program that exactly suits your needs.
  7. Events in a program include the ways a user interacts with the computer.Theseare things like clicking or double-clicking the mouse, typing in text, or pressingthe Enter keyAs a developer, you write code that runs in response to these events. If the user clicks on a button,the code for that event runs.
  8. is the virtual machine component of Microsoft&apos;s .NET framework and is responsible for managing the execution of .NET programs. In a process known as Just-in-time compilation, the compiled code is converted into machine instructions that, in turn, are executed by the computer&apos;s CPU. The CLR provides additional services including memory management, type safety and exception handling. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. It provides exception handling, Garbage collection and thread management. clr is common all the version of the .NET framework.
  9. &apos; The following assignment produces a COMPILER ERROR because &apos; the variable is not declared and Option Explicit is On.
  10. Place the line Option Strict On before the first line of code In VB.NET, you can typically convert any data type to any other data type implicitly. Data loss can occur when the value of one data type is converted to a data type with less precision or with a smaller capacity. However, you receive a run-time error message if data will be lost in such a conversion. Option Strict notifies you of these types of conversions at compile time so that you can avoid them.
  11. circumflex (ˆ), sometimescalled the caret or hat, for exponentiation