Professional Documents
Culture Documents
VISUAL BASIC. NET
VISUAL BASIC. NET
NET - COMP204
In VB.NET, you can accept user input from textboxes on a form. Here's an example:
1. Design the form: Add a TextBox control to your form. Name it TextBox1.
2. Access the input: Use the Text property of the TextBox to get the user's input.
vb
Dim userInput As String
userInput = TextBox1.Text
Option Strict
Option Strict is a setting in VB.NET that enforces strict data typing. When it is on, it restricts
implicit data type conversions that could result in data loss or runtime errors.
vb
Option Strict On
Dim number As Integer
number = "123" ' This will cause a compile-time error
- Implicit Conversion: The compiler automatically converts one data type to another. Risky, as it
might cause runtime errors or data loss.
vb
Dim num As Integer = 10
Dim dbl As Double = num ' Implicit conversion from Integer to Double
- Explicit Conversion: You explicitly convert a data type using conversion functions.
vb
Dim str As String = "123"
Dim num As Integer
num = Convert.ToInt32(str) ' Explicit conversion from String to Integer
Functions
Functions are blocks of code that perform a task and return a value.
vb
Function AddNumbers(a As Integer, b As Integer) As Integer
Return a + b
End Function
Procedures
Procedures (also known as Subs) are similar to functions but do not return a value.
vb
Sub ShowMessage(message As String)
MessageBox.Show(message)
End Sub
Exception Handling
vb
Try
' Code that may throw an exception
Catch ex As Exception
' Code to handle the exception
Finally
' Code that runs regardless of whether an exception was thrown
End Try
Scope
vb
Module Module1
Dim moduleLevelVar As Integer ' Module scope
Sub Main()
Dim localVar As Integer ' Local scope
End Sub
End Module
Data Types
Data types define the type of data a variable can hold. Common data types include:
- Integer
- Double
- String
- Boolean
- Date
vb
Dim age As Integer = 30
Dim name As String = "John"
Dim isEmployed As Boolean = True
Control
Controls are elements on a form that allow user interaction, like TextBox, Button, Label, etc.
Name Property
vb
TextBox1.Name = "txtUserName"
Conditional statements that execute code based on whether a condition is true or false.
vb
If age >= 18 Then
Console.WriteLine("Adult")
Else
Console.WriteLine("Minor")
End If
Do While Loop
vb
Dim i As Integer = 0
Do While i < 10
Console.WriteLine(i)
i += 1
Loop
Select Case
vb
Dim grade As Char = "A"
Select Case grade
Case "A"
Console.WriteLine("Excellent")
Case "B"
Console.WriteLine("Good")
Case "C"
Console.WriteLine("Average")
Case Else
Console.WriteLine("Other")
End Select
These concepts form the basics of programming in VB.NET. Understanding them will help you
develop robust applications.
When option strict is set to On and user attempt an implicit conversiotion that attempt to convert
a string to an interger, what will be the result at compile time? Explain your answer
When `Option Strict` is set to `On` in VB.NET, it disallows implicit data type conversions that
could result in data loss or unexpected behavior. If a user attempts an implicit conversion from a
string to an integer, it will result in a compile-time error.
Explanation
`Option Strict On` enforces strict data typing in VB.NET. This means:
1. No Implicit Narrowing Conversions: You cannot implicitly convert data types if there is a risk
of data loss or an error.
2. No Late Binding: All object types must be explicitly converted.
3. No Implicit Object Type Assumptions: It enforces early binding and type safety.
Example
```vb
Option Strict On
' Implicit conversion from String to Integer (invalid with Option Strict On)
intValue = strValue
```
With `Option Strict On`, the compiler will generate an error for the line `intValue = strValue`
because it is trying to implicitly convert a `String` to an `Integer`.
Error Message
```
Option Strict On disallows implicit conversions from 'String' to 'Integer'.
```
Correct Approach
```vb
Option Strict On
```vb
Option Strict On
Summary
Using input boxes to accept user input write an appllication that prompts the user to enter their
score and display the corresponding grade.
Task:
Use if then. . else to determine the grade (Use your own criteria)
NB: You should run this in visual studio and copy the code here.
Public Class Form1
Private Sub btnEnterScore_Click(sender As Object, e As EventArgs) Handles
btnEnterScore.Click
' Retrieve the score from the TextBox
Dim input As String = txtScore.Text
Dim score As Integer
Using a simple example of implicit or explicit conversion, demonstrate exception handling. NB:
Write and run the code in visual studio and copy the code here.
Explain the importance of declaring variables and choosing appropriate data types for storing
input.
Importance of Declaring Variables and Choosing Appropriate Data Types for Storing Input
2. Type Safety:
- Error Prevention: Declaring variables with specific data types helps catch errors at compile
time rather than at runtime. For example, if a variable is declared as an `Integer`, the compiler
will prevent assignments of non-integer values to that variable.
- Data Integrity: Using appropriate data types ensures that the data stored in variables is valid
and within expected ranges. For instance, using a `DateTime` type for dates prevents invalid date
formats.
3. Performance:
- Efficient Memory Usage: Choosing appropriate data types helps optimize memory usage. For
example, using `Byte` instead of `Integer` for values between 0 and 255 saves memory.
- Processing Speed: Some data types are more efficient for certain operations. For example,
integer arithmetic is generally faster than floating-point arithmetic.
4. Data Validation:
- Ensuring Correct Data: Using specific data types helps ensure that only valid data is stored in
variables. For instance, declaring a variable as `Decimal` for monetary values ensures that the
stored values can accurately represent currency.
- Simplified Validation Logic: With appropriate data types, the need for additional validation
logic can be reduced. For example, a boolean type (`Boolean`) inherently limits the value to
`True` or `False`.
Example
Consider a simple application that collects user input for age and salary:
```vb
Public Class Form1
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
' Declare variables with appropriate data types
Dim age As Integer
Dim salary As Decimal
In this example:
- Age: Declared as `Integer` to ensure it stores whole numbers only.
- Salary: Declared as `Decimal` to accurately represent monetary values.
- Validation: Uses `TryParse` methods to ensure the input is valid before processing.
Summary
By following these practices, developers can write more robust, efficient, and maintainable code.
Describe the difference between implicit and explicit type conversions, and provide examples of
each. Write a code snippet that demonstrates both types of conversions.
Examples
```vb
Dim strVal As String = "123"
Dim intVal As Integer
Try
' Explicit conversion from String to Integer
intVal = Convert.ToInt32(strVal)
Console.WriteLine($"Explicit Conversion: String '{strVal}' to Integer {intVal}")
Catch ex As FormatException
Console.WriteLine("Conversion failed: Invalid format")
End Try
```
Here's a complete VB.NET code snippet that demonstrates both implicit and explicit conversions
with exception handling:
```vb
Module Module1
Sub Main()
' Implicit Conversion Example
Dim intVal As Integer = 10
Dim doubleVal As Double
Try
' Explicit conversion from String to Integer
intConvertedVal = Convert.ToInt32(strVal)
Console.WriteLine($"Explicit Conversion: String '{strVal}' to Integer
{intConvertedVal}")
Catch ex As FormatException
Console.WriteLine("Conversion failed: Invalid format")
End Try
Explanation
1. Implicit Conversion:
- The integer value `intVal` is implicitly converted to a `Double` without any explicit cast.
- The conversion is safe and no data is lost because `Double` can accommodate all integer
values.
2. Explicit Conversion:
- The string `strVal` is explicitly converted to an integer using `Convert.ToInt32`.
- Exception handling (`Try...Catch`) is used to manage any potential `FormatException` if the
string is not a valid number.
This code can be run in a console application in Visual Studio to observe both types of
conversions and their behaviors.