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).
- Text – caption on the button
- BackColor – background color
- ForeColor – text color
- Location – position on form
- Image – displays image on button
- TabIndex – sets tab order
- Select() – activates the control
- NotifyDefault() – indicates default button
- GetPreferredSize() – gets suitable size
- ToString() – returns control name
- Click – button is clicked
- DoubleClick – double click
- GotFocus – control receives focus
- TextChanged – text changes
- Checked – whether selected
- Text – caption of radio button
- Appearance – visual style
- AutoCheck – automatic state change
- CheckAlign – check mark alignment
- PerformClick() – simulates a click programmatically
- CheckedChanged – selection changes
- AppearanceChanged – appearance changes
- 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
- BeginUpdate() – suspends drawing
- EndUpdate() – resumes drawing
- FindString() – finds matching item
- SelectAll() – selects text
- SelectedIndexChanged – selection changes
- DropDown – list opens
- DropDownClosed – list closes
- SelectionChangeCommitted – user changes selection
- Text – gets/sets text
- Multiline – enables multiple lines
- PasswordChar – masks password
- ReadOnly – makes text read-only
- MaxLength – maximum characters
- ScrollBars – adds scroll bars
- AppendText() – adds text
- Clear() – clears text
- Copy() – copies selection
- Paste() – pastes text
- Undo() – undo last action
- Click – textbox clicked
- DoubleClick – double click
- TextAlignChanged – alignment changes
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.
Uses Try…Catch…Finally blocks to handle errors in a controlled and readable way. It is object-oriented and more reliable.
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
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
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
| Feature | Structured | Unstructured |
|---|---|---|
| Approach | Try…Catch…Finally | On Error statements |
| Type | Modern | Old |
| Readability | High | Low |
| Reliability | More reliable | Less reliable |
| OOP support | Yes | No |
| Recommended | Yes | No |
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.
A procedure is a block of statements that performs a task but does not return any value.
SyntaxSub ProcedureName([parameters])
' statements
End Sub
Example
Module Module1
Sub ShowMessage()
MsgBox("Welcome to VB.NET")
End Sub
Sub Main()
ShowMessage()
End Sub
End Module
Features:
- Does not return a value
- Called using its name directly
- Uses Sub…End Sub
- Can take parameters
- Used for performing actions
A function is a block of code that performs a task and returns a value to the calling program.
SyntaxFunction 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
Features:
- Returns a value
- Uses Function…End Function
- Must specify return type
- Uses Return statement
- Can accept parameters
Difference Between Procedure and Function
| Feature | Procedure (Sub) | Function |
|---|---|---|
| Return value | No | Yes |
| Keyword | Sub | Function |
| Return type | Not required | Required |
| Usage | Performs action | Performs calculation |
| Call | Direct call | Used in expression |
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 occur when the user presses or releases keys on the keyboard while a control has focus.
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
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
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) _
Handles Me.KeyUp
MsgBox("Key Released: " & e.KeyCode.ToString())
End Sub
- Input validation
- Shortcut key handling
- Game controls
- Form navigation
Mouse events occur when the user performs actions using the mouse such as clicking, moving, or scrolling.
Private Sub Form1_MouseClick(sender As Object, _
e As MouseEventArgs) Handles Me.MouseClick
MsgBox("Mouse Clicked")
End Sub
Private Sub Form1_MouseDown(sender As Object, _
e As MouseEventArgs) Handles Me.MouseDown
MsgBox("Mouse Down")
End Sub
Private Sub Form1_MouseUp(sender As Object, _
e As MouseEventArgs) Handles Me.MouseUp
MsgBox("Mouse Up")
End Sub
Private Sub Form1_MouseMove(sender As Object, _
e As MouseEventArgs) Handles Me.MouseMove
Me.Text = "X=" & e.X & " Y=" & e.Y
End Sub
MouseEnter — pointer enters the control. MouseLeave — pointer leaves the control.
- Button click handling
- Drag and drop
- Drawing applications
- Interactive UI behavior
Difference Between Keyboard and Mouse Events
| Feature | Keyboard Events | Mouse Events |
|---|---|---|
| Input device | Keyboard | Mouse |
| Trigger | Key press/release | Click/move |
| Event args | KeyEventArgs | MouseEventArgs |
| Common use | Text input | UI interaction |
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.
A dynamic array is an array whose size can be changed at runtime using the ReDim statement. Size is not fixed at compile time.
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
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
A jagged array is an array of arrays where each row can have a different number of columns. It is not a rectangular matrix.
SyntaxDim 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
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
| Feature | Dynamic Array | Jagged Array |
|---|---|---|
| Size | Can change at runtime | Fixed per sub-array |
| Structure | Single array | Array of arrays |
| Shape | Linear | Irregular (non-rectangular) |
| Keyword used | ReDim | New with nested arrays |
| Memory | Reallocated | Separate arrays |