VB.NET Programming — Study Notes

Unit 03

Controls, Exception Handling, Procedures, Events & Arrays

5 Questions 6 Marks Each VB.NET
01
6 Marks Question

Button, RadioButton, ComboBox and TextBox Controls

In VB.NET Windows Forms, controls are GUI elements placed on forms to interact with users. Each control has properties (describe the control), methods (perform actions), and events (respond to user interactions).

Button
Button Control
A standard Windows button that generates a Click event when pressed.
Properties
  • Text – caption on the button
  • BackColor – background color
  • ForeColor – text color
  • Location – position on form
  • Image – displays image on button
  • TabIndex – sets tab order
Methods
  • Select() – activates the control
  • NotifyDefault() – indicates default button
  • GetPreferredSize() – gets suitable size
  • ToString() – returns control name
Events
  • Click – button is clicked
  • DoubleClick – double click
  • GotFocus – control receives focus
  • TextChanged – text changes
RadioButton
RadioButton Control
Provides mutually exclusive options — only one can be selected from a group.
Properties
  • Checked – whether selected
  • Text – caption of radio button
  • Appearance – visual style
  • AutoCheck – automatic state change
  • CheckAlign – check mark alignment
Methods
  • PerformClick() – simulates a click programmatically
Events
  • CheckedChanged – selection changes
  • AppearanceChanged – appearance changes
ComboBox
ComboBox Control
A combination of TextBox and ListBox that displays a drop-down list of items.
Properties
  • Items – collection of items
  • SelectedIndex – index of selected item
  • SelectedItem – currently selected item
  • Text – text in combo box
  • DropDownStyle – style of combo
  • Sorted – sorts items alphabetically
Methods
  • BeginUpdate() – suspends drawing
  • EndUpdate() – resumes drawing
  • FindString() – finds matching item
  • SelectAll() – selects text
Events
  • SelectedIndexChanged – selection changes
  • DropDown – list opens
  • DropDownClosed – list closes
  • SelectionChangeCommitted – user changes selection
TextBox
TextBox Control
Allows the user to enter and edit text at runtime. Can be single-line or multiline.
Properties
  • Text – gets/sets text
  • Multiline – enables multiple lines
  • PasswordChar – masks password
  • ReadOnly – makes text read-only
  • MaxLength – maximum characters
  • ScrollBars – adds scroll bars
Methods
  • AppendText() – adds text
  • Clear() – clears text
  • Copy() – copies selection
  • Paste() – pastes text
  • Undo() – undo last action
Events
  • Click – textbox clicked
  • DoubleClick – double click
  • TextAlignChanged – alignment changes
Conclusion Button, RadioButton, ComboBox, and TextBox are essential VB.NET controls used for user interaction. Each control provides specific properties, methods, and events that help developers build interactive and user-friendly Windows applications.
02
6 Marks Question

Structured and Unstructured Exception Handling in VB.NET

Exception handling in VB.NET is used to handle runtime errors and maintain normal program flow. VB.NET supports two types of exception handling: Structured and Unstructured.

Structured (Modern)

Uses Try…Catch…Finally blocks to handle errors in a controlled and readable way. It is object-oriented and more reliable.

Syntax
Try
    ' risky code
Catch ex As Exception
    ' handling code
Finally
    ' cleanup code
End Try
Example
Module Module1
    Sub Main()
        Try
            Dim a As Integer = 10
            Dim b As Integer = 0
            Dim c As Integer

            c = a \ b   ' causes error
        Catch ex As Exception
            MsgBox("Error occurred")
        Finally
            MsgBox("Program finished")
        End Try
    End Sub
End Module

Features:

  • Handles specific exceptions
  • Supports multiple Catch blocks
  • Finally always runs
  • High readability and safety
  • Recommended in VB.NET
Unstructured (Legacy)

Uses On Error statements. It is the older method, less flexible, and not recommended for modern applications.

Types of On Error:

  • On Error GoTo label
  • On Error Resume Next
  • On Error GoTo 0
Example (On Error GoTo)
Module Module1
    Sub Main()
        On Error GoTo ErrHandler

        Dim a As Integer = 10
        Dim b As Integer = 0
        Dim c As Integer

        c = a \ b

        Exit Sub

ErrHandler:
        MsgBox("Error occurred")
    End Sub
End Module

Features:

  • Old VB style
  • Uses labels and jumps
  • Harder to maintain
  • Less structured
  • Not recommended for new applications

Difference Between Structured and Unstructured Exception Handling

FeatureStructuredUnstructured
ApproachTry…Catch…FinallyOn Error statements
TypeModernOld
ReadabilityHighLow
ReliabilityMore reliableLess reliable
OOP supportYesNo
RecommendedYesNo
Conclusion VB.NET provides both structured and unstructured exception handling mechanisms. Structured exception handling using Try…Catch…Finally is the modern, safer, and recommended approach, while unstructured handling using On Error is the older method and should be avoided in new applications.
03
6 Marks Question

Procedure and Function in VB.NET

In VB.NET, procedures and functions are blocks of code used to perform specific tasks. They help in code reusability, modular programming, and better readability. Both are members of a module or class but differ mainly in whether they return a value.

Procedure (Sub)

A procedure is a block of statements that performs a task but does not return any value.

Syntax
Sub ProcedureName([parameters])
    ' statements
End Sub
Example
Module Module1
    Sub ShowMessage()
        MsgBox("Welcome to VB.NET")
    End Sub

    Sub Main()
        ShowMessage()
    End Sub
End Module
OutputDisplays: Welcome to VB.NET

Features:

  • Does not return a value
  • Called using its name directly
  • Uses Sub…End Sub
  • Can take parameters
  • Used for performing actions
Function

A function is a block of code that performs a task and returns a value to the calling program.

Syntax
Function FunctionName([parameters]) _
        As DataType
    ' statements
    Return value
End Function
Example
Module Module1
    Function Add(ByVal a As Integer, _
                 ByVal b As Integer) As Integer
        Return a + b
    End Function

    Sub Main()
        Dim result As Integer
        result = Add(10, 20)
        MsgBox(result)
    End Sub
End Module
Output30

Features:

  • Returns a value
  • Uses Function…End Function
  • Must specify return type
  • Uses Return statement
  • Can accept parameters

Difference Between Procedure and Function

FeatureProcedure (Sub)Function
Return valueNoYes
KeywordSubFunction
Return typeNot requiredRequired
UsagePerforms actionPerforms calculation
CallDirect callUsed in expression
Conclusion Procedures and functions are important building blocks in VB.NET. A procedure is used when no value needs to be returned, while a function is used when a result must be returned to the caller. Proper use of both improves modularity and code efficiency.
04
6 Marks Question

Keyboard and Mouse Events in VB.NET

In VB.NET Windows Forms, events are actions generated by the user while interacting with controls. Keyboard and mouse events allow the programmer to respond to user input such as key presses and mouse clicks.

Keyboard Events

Keyboard events occur when the user presses or releases keys on the keyboard while a control has focus.

01 KeyDown Occurs when a key is pressed down

Detects special keys (Ctrl, Alt, Function keys).

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) _
        Handles Me.KeyDown
    MsgBox("Key Down: " & e.KeyCode.ToString())
End Sub
02 KeyPress Occurs when a key producing a character is pressed

Used for character input validation.

Private Sub TextBox1_KeyPress(sender As Object, _
        e As KeyPressEventArgs) Handles TextBox1.KeyPress
    MsgBox("Key Pressed: " & e.KeyChar)
End Sub
03 KeyUp Occurs when a key is released
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) _
        Handles Me.KeyUp
    MsgBox("Key Released: " & e.KeyCode.ToString())
End Sub
Uses of Keyboard Events
  • Input validation
  • Shortcut key handling
  • Game controls
  • Form navigation
Mouse Events

Mouse events occur when the user performs actions using the mouse such as clicking, moving, or scrolling.

01 MouseClick Occurs when the mouse is clicked
Private Sub Form1_MouseClick(sender As Object, _
        e As MouseEventArgs) Handles Me.MouseClick
    MsgBox("Mouse Clicked")
End Sub
02 MouseDown Occurs when mouse button is pressed
Private Sub Form1_MouseDown(sender As Object, _
        e As MouseEventArgs) Handles Me.MouseDown
    MsgBox("Mouse Down")
End Sub
03 MouseUp Occurs when mouse button is released
Private Sub Form1_MouseUp(sender As Object, _
        e As MouseEventArgs) Handles Me.MouseUp
    MsgBox("Mouse Up")
End Sub
04 MouseMove Occurs when the mouse pointer moves
Private Sub Form1_MouseMove(sender As Object, _
        e As MouseEventArgs) Handles Me.MouseMove
    Me.Text = "X=" & e.X & " Y=" & e.Y
End Sub
05 MouseEnter / MouseLeave Pointer enters or leaves control

MouseEnter — pointer enters the control. MouseLeave — pointer leaves the control.

Uses of Mouse Events
  • Button click handling
  • Drag and drop
  • Drawing applications
  • Interactive UI behavior

Difference Between Keyboard and Mouse Events

FeatureKeyboard EventsMouse Events
Input deviceKeyboardMouse
TriggerKey press/releaseClick/move
Event argsKeyEventArgsMouseEventArgs
Common useText inputUI interaction
Conclusion Keyboard and mouse events are essential in VB.NET for handling user interactions. Keyboard events respond to key actions, while mouse events handle pointer actions. Proper use of these events helps in building responsive and interactive Windows applications.
05
6 Marks Question

Dynamic and Jagged Array in VB.NET

Arrays in VB.NET are used to store multiple values of the same type. Based on memory allocation and structure, arrays can be dynamic arrays or jagged arrays. These provide flexibility in handling data collections.

Dynamic Array

A dynamic array is an array whose size can be changed at runtime using the ReDim statement. Size is not fixed at compile time.

Syntax
Dim arrayName() As DataType
ReDim arrayName(size)
Example
Module Module1
    Sub Main()
        Dim arr() As Integer

        ReDim arr(4)   ' size = 5 elements

        arr(0) = 10
        arr(1) = 20
        arr(2) = 30

        MsgBox(arr(1))
    End Sub
End Module
Output20

ReDim Preserve — resizes without losing existing data:

ReDim Preserve arr(9)

Features:

  • Size decided at runtime
  • Uses ReDim statement
  • Flexible memory usage
  • Use Preserve to retain data
Jagged Array

A jagged array is an array of arrays where each row can have a different number of columns. It is not a rectangular matrix.

Syntax
Dim jaggedArray()() As DataType
Example
Module Module1
    Sub Main()
        Dim jagged()() As Integer = _
            New Integer(2)() {}

        jagged(0) = New Integer() {1, 2}
        jagged(1) = New Integer() {3, 4, 5}
        jagged(2) = New Integer() {6}

        MsgBox(jagged(1)(2))
    End Sub
End Module
Output5

Features:

  • Array of arrays
  • Rows can have different lengths
  • Memory efficient for irregular data
  • Access using double index arr(i)(j)

Difference Between Dynamic and Jagged Array

FeatureDynamic ArrayJagged Array
SizeCan change at runtimeFixed per sub-array
StructureSingle arrayArray of arrays
ShapeLinearIrregular (non-rectangular)
Keyword usedReDimNew with nested arrays
MemoryReallocatedSeparate arrays
Conclusion Dynamic arrays in VB.NET allow resizing of arrays during program execution, providing flexibility in memory management. Jagged arrays are arrays of arrays that support irregular data structures where each row can have a different size. Both are useful for handling dynamic data efficiently.