1/29
Visual Basic master in one flashcard!
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
If…Then Statement
Definition: Tests a condition. If it's true, a set of statements is executed; otherwise, nothing happens.
Syntax:
IF (condition) THEN
statements
ENDIF
Example:
IF age >= 18 THEN
Message “You are eligible to vote”
ENDIF
If…Then…Else Statement
Definition: Provides an alternative path. If the condition is true, one action happens; else, another does.
Syntax:
IF (condition) THEN
statements
ELSE
statements
ENDIF
Example:
IF age >= 18 THEN
Message “You are eligible to vote”
ELSE
Message “Sorry, you are not eligible to vote”
ENDIF
If…Then…ElseIf…Else Statement
Definition: Checks multiple exclusive conditions. The first true condition's statements are executed.
Syntax:
IF condition1 THEN
statements
ELSEIF condition2 THEN
statements
ELSEIF condition3 THEN
statements
ELSE
statements
ENDIF
Example:
IF age <= 4 THEN
Message “Your rate is free”
ELSEIF age <= 12 THEN
Message “Children’s rate”
ELSEIF age < 65 THEN
Message “Full rate”
ELSE
Message “Seniors”
ENDIF
Nested If Statements
Definition: Allows multiple condition checks inside one another. Enables deeper logical branching.
Syntax:
IF (expression1) THEN
IF (expression2) THEN
statement1
ELSE
statement2
ENDIF
ELSE
body-of-else
ENDIF
Syntax 2:
IF (expression1) THEN
body-of-if
ELSE
IF (expression2) THEN
statement1
ELSE
statement2
ENDIF
ENDIF
Syntax 3:
IF (expression1) THEN
IF (expression2) THEN
statement1
ELSE
statement2
ENDIF
ELSE
IF (expression3) THEN
statement3
ELSE
statement4
ENDIF
ENDIF
Select Case – Exact Match
Definition: Tests a single expression against multiple possible values. Cleaner than long If…ElseIf chains.
Syntax:
Select Case expression
Case value1
statements
Case value2
statements
Case Else
statements
End Select
Example:
Select Case byMonth
Case 1,3,5,7,8,10,12
number_of_days = 31
Case 2
number_of_days = 28
Case Else
number_of_days = 30
End Select
Select Case – Relational Test
Definition: Uses relational comparisons (e.g., <, >) to decide which block to execute.
Syntax:
Select Case expression
Case Is < value
statements
Case Is < value
statements
Case Else
statements
End Select
Example:
Select Case marks
Case Is < 50
Result = “Fail”
Case Is < 60
Result = “Grade B”
Case Is < 75
Result = “Grade A”
Case Else
Result = “Grade A+”
End Select
Select Case – Range Check
Definition: Evaluates if an expression falls within specific value ranges. Great for grouped conditions.
Syntax:
Select Case expression
Case value1 To value2
statements
Case value3 To value4
statements
Case Else
statements
End Select
Example:
Select Case Age
Case 2 To 4
Message “Prenursery”
Case 4 To 6
Message “Kindergarten”
Case 6 To 10
Message “Primary”
Case Else
Message “Others”
End Select
IF summary
Variables / Declaring Variables
Variables:
Store data in memory, like a textbox but not a control.
Must be given a name.
Declaring Variables:
Syntax: Dim v_Number1, v_Number2 As Integer
This must be placed in the declarations section at the start of the program.
Variable Types
Data Type | Description | Storage Requirements | Range of values |
Byte | Whole numbers | 1 byte | 0 to 255 |
Integer | Whole numbers | 2 bytes | -32,768 to 32,767 |
Long | Whole numbers | 4 bytes | Around –2 billion to 2 billion |
Single | Decimal numbers “floating point” number | 8 bytes | Around -1.79e308 to 1.79e308 with 15 digit precision |
Currency | To 4 decimal places “floating point” number | 8 bytes | + - 922,337,203,685,477.5808 |
String | Text | 1 byte per character | |
Boolean | True or False | 2 bytes | True (i.e. the value –1) or False (i.e. the value 0) |
Date | Valid date | 8 bytes |
Validation Techniques
Validation Techniques:
Input must be numeric (IsNumeric):
If IsNumeric(txtOne.Text) And IsNumeric(txtTwo.Text) Then
txtTotal.Text = Val(txtOne.Text) + Val(txtTwo.Text)
Else
MsgBox("Please enter a valid number")
End If
Input must be in a range:
If Val(txtPostcode.Text) <= 2999 Or Val(txtPostcode.Text) > 3999 Then
MsgBox("Illegal postcode. Please try again")
End If
Character length restriction (Len):
If Len(txtSurname.Text) > 20 Then
MsgBox("Surname too long, maximum 20 characters")
End If
Validating text input (<>):
If txtAnswer.Text <> "Yes" And txtAnswer.Text <> "No" Then
MsgBox("Your answer must be Yes or No")
End If
Validate for Upper/Lowercase:
If UCase(txtAnswer.Text) = "YES" Then
' Proceed with validation
End If
Do...Loop Until / Do...Loop While:
Do...Loop Until:
Runs until the condition is true (checked after each iteration).
Do
'Loop code here
Loop Until condition
Do...Loop While:
Runs while the condition is true (checked after each iteration).
Do
'Loop code here
Loop While condition
Do Until...Loop:
Same as Do...Loop While, checks condition at the beginning of each iteration.
Do Until condition
'Loop code here
Loop
Do While...Loop:
Same as Do...Loop Until, checks condition at the beginning.
Do While condition
'Loop code here
Loop
Array
Arrays are used to store multiple values of the same data type in a single variable.
Declared using the Dim
statement:
Dim myData() As Integer
Dim myData(9) As String
Declaring and Initializing Arrays:
You can declare and initialize arrays at the same time:
Dim myData() As Integer = {11, 12, 22, 7, 47, 32}
Dim students() As String = {"John", "Alice", "Antony"}
Fixed - Size Arrays
Fixed-size arrays have a predetermined number of elements:
Dim students(2) As String
students(0) = "John"
students(1) = "Alice"
students(2) = "Antony"
Dynamic Arrays
Can grow in size as needed:
Dim nums() As Integer
ReDim nums(1)
nums(0) = 12
nums(1) = 23
ReDim Preserve nums(2)
nums(2) = 35
Retrieving Array Elements
Access array elements using their index:
txtDisplay.Text = students(1) ' Displays "Alice"
txtDisplay.Text = myData(0) ' Displays "11"
Adding New Elements (Dynamic Arrays)
Only possible with dynamic arrays using ReDim
:
ReDim Preserve nums(3) ' Resize and preserve old values
Join Function
Combine array elements into a single string:
Dim classmates As String = Join(students, ", ")
' Result: "John, Alice, Antony"
Loops & Arrays
Example of looping through an array:
For Each element As String In array
Console.Write(element)
Console.Write("... ")
Next
For a ComboBox:
For Each element As String In array
comboBox.Items.Add(element)
Next
Summary: Arrays
Arrays store multiple data elements of the same type.
Dynamic arrays can be resized with ReDim
; fixed-size arrays cannot.
Indexes: First element is at index 0, last at index n-1
.
Use Erase
to delete arrays.
Use Split
and Join
for splitting and combining arrays of strings.
What is a DataGridView?
A control in VB.NET for displaying and manipulating data in a grid format.
Key Features:
Displays data in rows and columns.
Supports adding, editing, deleting, and sorting data.
Can be bound to databases, arrays, or lists, or populated manually.
Customizable styling.
Setting Up a DataGridView
Add DataGridView (DGV) to the form.
Uncheck properties: Enable Adding, Editing, Deleting.
Add columns:
Click ‘Add Column…’.
Enter Name and Header Text for each column (e.g., fName
, lName
, score
).
Click ‘Add’ for each column.
Adjust column width: Select DGV → Triangle (top right) → Edit Columns… → Change column width.
Using Loops & Arrays with DataGridView
Example arrays to load data into DGV:
aFirst() As String = {"Mateo", "Aisha", "Hiroshi", "Elena", "Liam", "Mei", "Ravi"}
aLast() As String = {"Gonzalez", "Khan", "Takahashi", "Rodriguez", "O'Connor", "Zhang", "Patel"}
aScore() As Integer = {90, 45, 78, 87, 92, 55, 76}
Load data into DGV as the form loads (using loops).
Averaging a Column
Calculate the total and average of a column (e.g., scores):
For Each row As DataGridViewRow In DataGridView1.Rows
total += row.Cells(2).Value
count += 1
Next
average = total / count
Apply rounding to the average for formatting.
Deleting Rows
To delete a row:
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
Validation: Ensure a row is selected before deleting.
Sorting Rows
Clicking on column headers sorts columns.
Programmatically sort:
DataGridView1.Sort(DataGridView1.Columns(2), ComponentModel.ListSortDirection.Ascending)
DataGridView1.Sort(DataGridView1.Columns(2), ComponentModel.ListSortDirection.Descending)
Why Write to a Text File?
Data is stored temporarily in RAM. When the program closes, data is lost.
To permanently store data (e.g., in ROM), data needs to be saved to an external file.
You can export data to various file types: .txt
, .docx
, .xlsx
, .xml
, etc.
Demo: Writing Data to a Text File
Import Libraries:
Add System.IO
to the top of your code:
Imports System.IO
Setting Up the Button:
Create a button in the form that will trigger the file-saving process.
Example: Button1_Click
event handler.
Getting Data in Organised Format:
Use a variable to hold the data as a String.
Example File Content: If you want to get data from a DataGridView:
Use vbCrLf
for new lines.
Example:
Dim fileData As String = ""
For Each row As DataGridViewRow In DataGridView1.Rows
fileData &= row.Cells(0).Value.ToString() & vbCrLf
Next
Writing Data to a File
Writing Data to a File:
Use StreamWriter to write data:
Using writer As New StreamWriter("C:\path\to\file.txt")
writer.Write(fileData)
End Using
The Using block ensures proper disposal of resources after the writing process is complete.
Getting an Average and Writing & Locating File
Getting an Average and Writing:
If you're writing averages (e.g., class average):
Dim avg As Double = total / count
fileData &= "Class Average: " & avg.ToString() & vbCrLf
Locating the File:
After saving, your file will be found in the following directory for VS2022:
Project Folder/Bin/Debug/net8.0-windows