Chapter 3: Variables & Calculations

Starting Out with Visual Basic 8e — Tony Gaddis | Quiz 3 due Jun 12

3.1 — Gathering Text Input

Use a TextBox control to let users type text into your application.

Dim userName As String userName = TextBox1.Text
  • Text property: gets/sets the text displayed in the box
  • Text is always a String — must convert for numbers
  • MultiLine property: allows multiple lines
  • ReadOnly property: prevents user editing
  • Clear() method: erases all text
  • Focus() method: moves cursor to this box
💡 After processing input, use TextBox1.Clear() and TextBox1.Focus() to reset for next entry.

3.2 — Variables and Data Types

A variable is a named storage location in memory. Declare with Dim.

Dim age As Integer Dim price As Decimal = 29.99D Dim name As String = "Alice" Dim isActive As Boolean = True
TypeStoresExample
IntegerWhole numbers (-2B to 2B)Dim x As Integer = 5
DoubleFloating-point numbersDim y As Double = 3.14
DecimalHigh-precision (money)Dim z As Decimal = 19.99D
StringTextDim s As String = "Hello"
BooleanTrue/FalseDim b As Boolean = True
CharSingle characterDim c As Char = "A"c
💡 Naming rules: Must start with letter, no spaces, no keywords, use camelCase (e.g., totalSales).

3.3 — Performing Calculations

VB supports standard arithmetic operators:

+ ' Addition - ' Subtraction * ' Multiplication / ' Floating-point division (3 / 2 = 1.5) \ ' Integer division (3 \ 2 = 1) ^ ' Exponentiation (2 ^ 3 = 8) Mod ' Modulus / remainder (7 Mod 3 = 1)

Operator Precedence (highest to lowest):

  1. Parentheses ( )
  2. Exponentiation ^
  3. Multiplication/division * / \
  4. Modulus Mod
  5. Addition/subtraction + -
' Calculate total with tax Dim subtotal As Decimal = 45.00D Dim taxRate As Decimal = 0.0825D Dim total As Decimal = subtotal + (subtotal * taxRate)

3.4 — Mixing Different Data Types

VB converts types automatically (implicit conversion) unless Option Strict is On.

Option Strict On ' Forces explicit conversions Option Strict Off ' Allows automatic widening

Type conversion functions:

CInt(value) ' → Integer CDbl(value) ' → Double CDec(value) ' → Decimal CStr(value) ' → String CBool(value) ' → Boolean
💡 Always use CDec() for currency/money calculations to avoid floating-point rounding errors.

3.5 — Formatting Numbers and Strings

' Format function Format(1234.5, "$#,##0.00") ' → "$1,234.50" ' ToString with format specifiers price.ToString("C") ' Currency: "$1,234.50" price.ToString("N2") ' Number: "1,234.50" price.ToString("P1") ' Percent: "12.3 %" price.ToString("F0") ' Fixed: "1235"
  • "C" or "c" — Currency format with $ sign and 2 decimals
  • "N" or "n" — Number with commas and decimals
  • "P" or "p" — Percentage (multiplies by 100)
  • "F" or "f" — Fixed-point with specified decimals

3.6 — Class-Level Variables

Declared outside any procedure, inside the form class. Accessible from all procedures in the form.

Public Class Form1 ' Class-level variable — available everywhere in this form Private totalSales As Decimal = 0D Private Sub Button1_Click(...) Handles Button1.Click totalSales += CDec(TextBox1.Text) End Sub End Class
💡 Class-level variables retain their value between procedure calls. Local variables are recreated each time.

3.7 — Exception Handling

Use TryParse to safely convert input without crashing:

Dim number As Integer If Integer.TryParse(TextBox1.Text, number) Then MessageBox.Show("Valid number: " & number.ToString()) Else MessageBox.Show("Invalid input!") End If

Or use Try-Catch blocks:

Try result = CDec(TextBox1.Text) / CDec(TextBox2.Text) lblResult.Text = result.ToString("C") Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try
💡 TryParse is preferred for input validation — doesn't throw exceptions, just returns True/False.

Practice Quiz — Chapter 3

Test your knowledge. 25 questions covering variables, calculations, types, and more.

0 / 25
questions answered correctly

Flashcards — Chapter 3

Click a card to flip it. Review key terms and concepts.

What is a variable?
A named location in memory that stores a value. Declared with the Dim keyword.

Card 1 / 30

Cheat Sheet — Chapter 3

Quick reference for Quiz 3. All the essentials in one place.

🔑 Key Syntax

Dim variableName As DataType [= initialValue] Const PI As Double = 3.14159 Dim result As Decimal = CDec(TextBox1.Text) * 0.0825D

📊 Data Types Quick Reference

TypeSizeRange / ValuesSuffix
Integer32-bit-2,147,483,648 to 2,147,483,647
Double64-bit±4.94×10⁻³²⁴ to ±1.8×10³⁰⁸R or #
Decimal128-bit±7.9×10⁻²⁸ to ±7.9×10²⁸ (28-29 digits)D or @
Stringvaries0 to ~2 billion chars" "
Boolean16-bitTrue or False
Char16-bitSingle Unicode char"A"c

🔄 Conversion Functions

FunctionResult Type
CInt(value)Integer (rounds)
CDbl(value)Double
CDec(value)Decimal ← use for money!
CStr(value)String
CBool(value)Boolean
CChar(value)Char

📋 Format Specifiers

SpecifierNameExample (1234.5)
"C"Currency$1,234.50
"N2"Number (2 decimals)1,234.50
"F0"Fixed (0 decimals)1235
"P1"Percent12.3%
"E2"Scientific1.23E+003

⚠️ Common Pitfalls

  • Integer division: 7 / 3 = 2.333 but 7 \ 3 = 2 (backslash = integer division)
  • Mod: 17 Mod 4 = 1 (remainder)
  • Decimal suffix: Always use 19.99D not 19.99 for Decimal literals
  • Option Strict: When On, all conversions must be explicit (use CInt, CDec, etc.)
  • TryParse: Integer.TryParse(text, variable) — returns True/False, puts value in variable
  • CurrentCulture: ToString("C") respects system locale for currency symbol