0% found this document useful (0 votes)
4 views22 pages

VB NET Study Notes

This document serves as a comprehensive guide for students learning VB.NET programming, covering key concepts such as program structure, data types, control structures, and event handling. It includes detailed explanations and examples for various topics, including Windows Forms applications and database connectivity with ADO.NET. The notes are structured to facilitate understanding and practical application of VB.NET programming principles.

Uploaded by

lenkoya.james
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

VB NET Study Notes

This document serves as a comprehensive guide for students learning VB.NET programming, covering key concepts such as program structure, data types, control structures, and event handling. It includes detailed explanations and examples for various topics, including Windows Forms applications and database connectivity with ADO.NET. The notes are structured to facilitate understanding and practical application of VB.NET programming principles.

Uploaded by

lenkoya.james
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

VB.

NET
Programming Study Notes

A Comprehensive Guide for Students


[Link] Programming - Complete Study Notes

Table of Contents
(Right-click and select "Update Field" to refresh page numbers)

1. Introduction to [Link].....................................................................................................................3

2. Program Structure............................................................................................................................4

3. Data Types, Variables and Constants.................................................................................................5

4. Control Structures............................................................................................................................6

5. Arrays...............................................................................................................................................9

6. Expressions and Operators.............................................................................................................10

7. Type Conversions............................................................................................................................12

8. Windows Forms Applications..........................................................................................................14

9. Event Handling...............................................................................................................................16

10. Dialog Forms................................................................................................................................18

11. Three-Tier Architecture.................................................................................................................20

12. Database Connectivity with [Link]...........................................................................................23

Page 2
[Link] Programming - Complete Study Notes

1. Introduction to [Link]
[Link] (Visual Basic .NET) is a modern, object-oriented programming language developed by
Microsoft. It is part of the .NET framework and is used to create Windows applications, web
applications, and more.

1.1 Key Features of [Link]


• Object-Oriented:[Link] fully supports OOP principles including encapsulation, inheritance,
and polymorphism.

• Platform Independent:Applications run on the Common Language Runtime (CLR), making


them portable across platforms.

• Rich Library:The .NET Framework provides extensive libraries for file I/O, networking,
database access, and GUI development.

• Automatic Memory Management:The garbage collector automatically handles memory


allocation and deallocation.

1.2 The .NET Framework


The .NET Framework is a software development platform that provides:

0. Common Language Runtime (CLR):The execution engine that manages running applications.

1. Framework Class Library (FCL):A comprehensive collection of reusable classes and


components.

2. Development Tools:Visual Studio IDE for building, debugging, and deploying applications.

Page 3
[Link] Programming - Complete Study Notes

2. Program Structure
Every [Link] program follows a standard structure with imports, modules, and the Main
method as the entry point.

2.1 Basic Program Structure


A simple [Link] program consists of the following components:
Imports System

Module Program
Sub Main()
' This is the entry point of the program
[Link]("Hello, World!")
End Sub
End Module

2.2 Components Explained


Declares namespaces needed for the program. System is commonly used for
Imports
basic I/O operations.

Module A container for code. In [Link], code must be placed inside a Module or Class.

The entry point where program execution begins. Every application must have
Sub Main()
one Main method.

[Link]() A method to output text to the console window.

' Comment Single-line comments start with an apostrophe.

Page 4
[Link] Programming - Complete Study Notes

3. Data Types, Variables and Constants

3.1 Common Data Types


[Link] supports various data types for storing different kinds of data:

Data Type Example Value Description

Integer 25 Whole numbers from -2,147,483,648 to 2,147,483,647

Long 1000000 Large whole numbers

Double 99.99 Floating-point numbers with decimal places

Decimal 123.456D High-precision decimal numbers for financial calculations

String Hello Text data enclosed in double quotes

Boolean True/False Logical values representing true or false

Date 01/01/2024 Date and time values

Char A Single character

3.2 Variable Declaration


Variables are declared using the Dim keyword followed by the variable name and data type:
Dim age As Integer = 25
Dim price As Double = 99.99
Dim name As String = "John"
Dim isAvailable As Boolean = True

3.3 Constants
Constants are values that cannot be changed during program execution. They are declared using the
Const keyword:
Const Pi As Double = 3.14159
Const MaxScore As Integer = 100
Const AppName As String = "MyApplication"

Constants improve code readability and maintainability. Use them for values that should never
change, such as mathematical constants or application settings.

Page 5
[Link] Programming - Complete Study Notes

4. Control Structures
Control structures determine the flow of program execution based on conditions and loops.

4.1 If...Then...Else Statements


The If statement executes code based on a condition:
Dim number As Integer = 10

If number > 5 Then


[Link]("Number is greater than 5")
ElseIf number = 5 Then
[Link]("Number equals 5")
Else
[Link]("Number is less than 5")
End If

4.2 Select Case Statement


Select Case provides a cleaner way to handle multiple conditions compared to multiple If statements:
Dim day As Integer = 3

Select Case day


Case 1
[Link]("Monday")
Case 2
[Link]("Tuesday")
Case 3
[Link]("Wednesday")
Case 4, 5
[Link]("Thursday or Friday")
Case Else
[Link]("Weekend")
End Select

4.3 Loops

For...Next Loop
Used when you know the exact number of iterations:
' Count from 1 to 5
For i As Integer = 1 To 5
[Link]("Iteration: " & i)
Next

' Count with a step


For i As Integer = 10 To 0 Step -2
[Link](i) ' Outputs: 10, 8, 6, 4, 2, 0
Next

Do...While Loop
Repeats while a condition is true:

Page 6
[Link] Programming - Complete Study Notes

Dim counter As Integer = 1

Do While counter <= 5


[Link]("Counter: " & counter)
counter += 1 ' Increment counter
Loop

Do...Until Loop
Repeats until a condition becomes true:
Dim counter As Integer = 1

Do Until counter > 5


[Link]("Counter: " & counter)
counter += 1
Loop

For Each Loop


Iterates through each element in a collection:
Dim fruits As String() = {"Apple", "Banana", "Orange"}

For Each fruit In fruits


[Link](fruit)
Next

Page 7
[Link] Programming - Complete Study Notes

5. Arrays
Arrays store multiple values of the same data type in a single variable.

5.1 Declaring and Initializing Arrays


' Method 1: Declare and initialize together
Dim fruits As String() = {"Apple", "Banana", "Orange"}

' Method 2: Declare with size, then assign values


Dim numbers(4) As Integer ' Array with 5 elements (0 to 4)
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
numbers(3) = 40
numbers(4) = 50

' Method 3: Using New keyword


Dim scores As Integer() = New Integer(2) {85, 90, 95}

5.2 Accessing Array Elements


Dim names As String() = {"Alice", "Bob", "Charlie"}

' Access individual elements (index starts at 0)


[Link](names(0)) ' Outputs: Alice
[Link](names(1)) ' Outputs: Bob

' Get array length


[Link]([Link]) ' Outputs: 3

5.3 Multidimensional Arrays


' 2D array (matrix)
Dim matrix(2, 2) As Integer
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(1, 0) = 3
matrix(1, 1) = 4

' Initialize 2D array


Dim grid(,) As Integer = {{1, 2, 3}, {4, 5, 6}}

Page 8
[Link] Programming - Complete Study Notes

6. Expressions and Operators


Expressions combine operands (variables/values) and operators to produce results.

6.1 Arithmetic Operators


Operator Name Description

+ Addition Adds two values

- Subtraction Subtracts second value from first

* Multiplication Multiplies two values

/ Division Divides first value by second

Mod Modulus Returns remainder of division

^ Exponentiation Raises first value to power of second

6.2 Arithmetic Expression Examples


Dim num1 As Integer = 10
Dim num2 As Integer = 3

Dim sum As Integer = num1 + num2 ' 13


Dim difference As Integer = num1 - num2 ' 7
Dim product As Integer = num1 * num2 ' 30
Dim quotient As Double = num1 / num2 ' 3.333...
Dim remainder As Integer = num1 Mod num2 ' 1
Dim power As Double = num1 ^ num2 ' 1000 (10^3)

6.3 Logical Operators


Logical operators combine Boolean values and are commonly used in conditional statements:

Operator Name Description

And Logical AND True if both conditions are true

Or Logical OR True if at least one condition is true

Not Logical NOT Reverses the Boolean value

AndAlso Short-circuit AND And that stops if first is false (more efficient)

OrElse Short-circuit OR Or that stops if first is true (more efficient)

6.4 Logical Expression Examples


Dim isAdult As Boolean = True
Dim hasID As Boolean = False

Page 9
[Link] Programming - Complete Study Notes

' AND - both must be true


If isAdult And hasID Then
[Link]("Entry allowed")
End If

' OR - at least one must be true


If isAdult Or hasID Then
[Link]("At least one condition met")
End If

' NOT - negation


If Not hasID Then
[Link]("ID is required")
End If

' Short-circuit operators (more efficient)


If isAdult AndAlso hasID Then ' Stops if isAdult is False
[Link]("Entry allowed")
End If

Page 10
[Link] Programming - Complete Study Notes

7. Type Conversions
Type conversion is the process of changing a value from one data type to another.

7.1 Implicit Conversion


[Link] automatically performs implicit conversions when there is no risk of data loss:
Dim smallNum As Integer = 100
Dim bigNum As Long = smallNum ' Implicit: Integer to Long (safe)

Dim intVal As Integer = 50


Dim dblVal As Double = intVal ' Implicit: Integer to Double (safe)

7.2 Explicit Conversion


Explicit conversions require conversion functions when data loss might occur:

Function Converts To Example

CInt() Integer CInt("123") returns 123

CLng() Long CLng("1000000") returns 1000000

CDbl() Double CDbl("99.99") returns 99.99

CDec() Decimal CDec("123.456") returns 123.456

CStr() String CStr(100) returns "100"

CDate() Date CDate("01/01/2024") returns date

CBool() Boolean CBool(1) returns True

CChar() Char CChar("A") returns 'A'

7.3 Conversion Examples


' String to numeric
Dim strNumber As String = "123"
Dim num As Integer = CInt(strNumber) ' 123

' Numeric to string


Dim age As Integer = 25
Dim strAge As String = CStr(age) ' "25"

' String to date


Dim strDate As String = "10/01/2024"
Dim dt As Date = CDate(strDate)

' Double to Integer (truncates decimal)


Dim price As Double = 99.99
Dim intPrice As Integer = CInt(price) ' 100 (rounded)

Always validate user input before conversion to prevent runtime errors. Use TryParse methods or

Page 11
[Link] Programming - Complete Study Notes

exception handling for safer conversions.

Page 12
[Link] Programming - Complete Study Notes

8. Windows Forms Applications


Windows Forms is a GUI framework for building desktop applications with visual controls like
buttons, text boxes, and labels.

8.1 Creating a Windows Forms Application


Steps to create a Windows Forms project in Visual Studio:

3. Create Project:Open Visual Studio and create a new Windows Forms App (.NET Framework)
project.

4. Design the Form:Drag and drop controls from the Toolbox onto the form.

5. Set Properties:Modify control properties (Name, Text, Size, etc.) in the Properties window.

6. Write Event Code:Double-click controls to create event handlers and write code.

8.2 Common Controls


Control Common Properties Purpose

Button Text, Name, Enabled Triggers an action when clicked

TextBox Text, Name, ReadOnly Accepts user text input

Label Text, Name, Font Displays read-only text

ComboBox Items, SelectedItem Dropdown list of options

ListBox Items, SelectedIndex Displays list of items

CheckBox Checked, Text Boolean option selector

RadioButton Checked, GroupName Single option selector

DataGridView DataSource, Columns Displays tabular data

8.3 Simple Button Click Example


Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) _n
Handles [Link]
[Link]("Button was clicked!")
End Sub
End Class

Page 13
[Link] Programming - Complete Study Notes

9. Event Handling
Event handling allows programs to respond to user actions like clicks, key presses, and mouse
movements.

9.1 What is an Event?


An event is an action or occurrence that the program responds to. Common events include:

• Click:Triggered when a user clicks a control.

• TextChanged:Triggered when text in a text box changes.

• MouseMove:Triggered when the mouse moves over a control.

• KeyPress:Triggered when a key is pressed.

• Load:Triggered when a form loads.

9.2 Event Handler Syntax


Private Sub ControlName_EventName(_n ByVal sender As Object, _n ByVal
e As EventArgs) _n Handles [Link]
' Event handling code here
End Sub

9.3 Event Handler Examples


' Button Click Event
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) _n Handles
[Link]
[Link] = "Hello, " & [Link]
End Sub

' TextBox TextChanged Event


Private Sub txtInput_TextChanged(sender As Object, e As EventArgs) _n
Handles [Link]
[Link] = "Characters: " & [Link]
End Sub

' MouseMove Event


Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) _n
Handles [Link]
[Link] = "X: " & e.X & " Y: " & e.Y
End Sub

9.4 Modifying Properties in Event Handlers


Private Sub btnChangeColor_Click(sender As Object, e As EventArgs) _n
Handles [Link]
' Change text and background color
[Link] = "Welcome to [Link]!"
[Link] = [Link]
[Link] = [Link]

Page 14
[Link] Programming - Complete Study Notes

' Enable/Disable controls


[Link] = False
[Link] = True
End Sub

Page 15
[Link] Programming - Complete Study Notes

10. Dialog Forms


Dialog forms provide ways to interact with users through pop-up windows for messages, file
operations, and more.

10.1 MessageBox
MessageBox displays information and captures user responses:
' Simple message
[Link]("Operation completed successfully")

' Message with title


[Link]("File saved", "Success")

' Message with buttons


Dim result As DialogResult = [Link](_n "Do you want to save
changes?", _n "Confirm", _n [Link])

If result = [Link] Then


' Save the file
ElseIf result = [Link] Then
' Discard changes
Else
' Cancel operation
End If

10.2 OpenFileDialog
Allows users to browse and select files:
Private Sub btnOpen_Click(sender As Object, e As EventArgs) _n Handles
[Link]
Dim openFileDialog As New OpenFileDialog()
[Link] = "Open a File"
[Link] = "Text Files|*.txt|All Files|*.*"

If [Link]() = [Link] Then


[Link] = [Link]
' Read file content
[Link] =
[Link]([Link])
End If
End Sub

10.3 SaveFileDialog
Allows users to specify where to save files:
Private Sub btnSave_Click(sender As Object, e As EventArgs) _n Handles
[Link]
Dim saveFileDialog As New SaveFileDialog()
[Link] = "Save File"
[Link] = "Text Files|*.txt|All Files|*.*"
[Link] = "[Link]"

If [Link]() = [Link] Then


[Link]([Link],

Page 16
[Link] Programming - Complete Study Notes

[Link])
[Link]("File saved successfully!")
End If
End Sub

Page 17
[Link] Programming - Complete Study Notes

11. Three-Tier Architecture


Three-tier architecture separates an application into three logical layers for better organization,
maintainability, and scalability.

11.1 The Three Layers

Presentation Layer (UI)


Handles all user interface elements and user interactions. Contains forms, buttons, labels, and event
handlers.

Business Logic Layer (BLL)


Contains the core business rules, calculations, and data validation. Acts as a mediator between UI
and data access.

Data Access Layer (DAL)


Handles all database operations including queries, inserts, updates, and deletes. Isolates database
details from other layers.

11.2 Layer Communication Flow


User Action -> Presentation Layer -> Business Logic Layer -> Data Access
Layer -> Database
<- <-
<-

11.3 Implementation Example


' ========== PRESENTATION LAYER ==========
Public Class UserForm
Private Sub btnAddUser_Click(sender As Object, e As EventArgs) _n
Handles [Link]
Dim user As New User()
[Link] = [Link]
[Link] = [Link]

' Call Business Logic Layer


[Link](user)
[Link]("User added successfully!")
End Sub
End Class

' ========== BUSINESS LOGIC LAYER ==========


Public Class UserBLL
Public Shared Sub AddUser(user As User)
' Validate input
If [Link]([Link]) Then
Throw New Exception("Name is required")
End If

' Call Data Access Layer

Page 18
[Link] Programming - Complete Study Notes

[Link](user)
End Sub
End Class

' ========== DATA ACCESS LAYER ==========


Public Class UserDAL
Public Shared Sub SaveUser(user As User)
Using conn As New SqlConnection(connectionString)
Dim query As String = "INSERT INTO Users (Name, Email) VALUES
(@Name, @Email)"
Using cmd As New SqlCommand(query, conn)
[Link]("@Name", [Link])
[Link]("@Email", [Link])
[Link]()
[Link]()
End Using
End Using
End Sub
End Class

11.4 Benefits of Three-Tier Architecture


• Separation of Concerns:Each layer has a specific responsibility, making code easier to
understand and maintain.

• Reusability:Business logic can be reused across different UI implementations (desktop, web,


mobile).

• Testability:Each layer can be tested independently, improving code quality.

• Scalability:Individual layers can be scaled or modified without affecting others.

Page 19
[Link] Programming - Complete Study Notes

12. Database Connectivity with [Link]


[Link] (ActiveX Data Objects for .NET) is a set of classes for accessing and manipulating data
in databases.

12.1 Key [Link] Components


Component Description

SqlConnection Establishes connection to SQL Server database

SqlCommand Executes SQL queries and stored procedures

SqlDataReader Reads data from database in forward-only stream

DataSet In-memory cache of data from multiple tables

DataTable In-memory representation of a single database table

SqlDataAdapter Bridge between DataSet and database for retrieving/updating data

SqlTransaction Manages database transactions for data integrity

12.2 Database Connection


Imports [Link]

Public Class DatabaseConnection


Private connectionString As String = _n
"Server=YOUR_SERVER;Database=YOUR_DB;Integrated Security=True;"

Public Function GetConnection() As SqlConnection


Return New SqlConnection(connectionString)
End Function
End Class

12.3 Executing SQL Queries


' INSERT Example
Public Sub AddItem(itemName As String, stockLevel As Integer)
Dim query As String = "INSERT INTO Inventory (ItemName, StockLevel) "
query &= "VALUES (@ItemName, @StockLevel)"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
' Add parameters (prevents SQL injection)
[Link]("@ItemName", itemName)
[Link]("@StockLevel", stockLevel)

[Link]()
[Link]()
End Using
End Using
End Sub

Page 20
[Link] Programming - Complete Study Notes

12.4 Retrieving Data with DataReader


Public Sub DisplayAllItems()
Dim query As String = "SELECT * FROM Inventory"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
[Link]()
Using reader As SqlDataReader = [Link]()
While [Link]()
[Link](reader("ItemName") & " - " & _n
reader("StockLevel"))
End While
End Using
End Using
End Using
End Sub

12.5 Using DataSet and DataAdapter


Public Function GetAllItems() As DataTable
Dim query As String = "SELECT * FROM Inventory"
Dim ds As New DataSet()

Using conn As New SqlConnection(connectionString)


Dim adapter As New SqlDataAdapter(query, conn)
[Link](ds, "Inventory")
End Using

Return [Link]("Inventory")
End Function

12.6 Database Transactions


Public Sub TransferStock(fromItem As String, toItem As String, amount As
Integer)
Using conn As New SqlConnection(connectionString)
[Link]()
Dim transaction As SqlTransaction = [Link]()

Try
' Deduct from source
Dim cmd1 As New SqlCommand(_n "UPDATE Inventory
SET StockLevel = StockLevel - @Amount "
& "WHERE ItemName = @ItemName", conn, transaction)
[Link]("@Amount", amount)
[Link]("@ItemName", fromItem)
[Link]()

' Add to destination


Dim cmd2 As New SqlCommand(_n "UPDATE Inventory
SET StockLevel = StockLevel + @Amount "
& "WHERE ItemName = @ItemName", conn, transaction)
[Link]("@Amount", amount)
[Link]("@ItemName", toItem)
[Link]()

' Commit if both succeed


[Link]()
[Link]("Transfer successful")

Catch ex As Exception
' Rollback on error

Page 21
[Link] Programming - Complete Study Notes

[Link]()
[Link]("Transfer failed: " & [Link])
End Try
End Using
End Sub

Always use parameters (AddWithValue) instead of string concatenation to prevent SQL injection
attacks.

Page 22

You might also like