Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

VISUAL BASIC .

NET - COMP204

VCAMPUS MOCK EXAMS.

1. How to accept user inputs from textboxes


2. Option Strict
3. Implicit and Explicit Conversions
4. Functions
5. Procedures
6. Exception Handling
7. Scope
8. Datatype
9. Control
10. Name Property
11. If then ... Else
12. Do while loop
13. Select Case

How to Accept User Inputs from Textboxes

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.

- With Option Strict On: Prevents implicit conversions.


- With Option Strict Off: Allows implicit conversions.

vb
Option Strict On
Dim number As Integer
number = "123" ' This will cause a compile-time error

Implicit and Explicit Conversions

- 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

Exception handling in VB.NET is done using Try...Catch...Finally.

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

Scope refers to the accessibility of variables and methods. It can be:

- Local Scope: Accessible only within the block where it is declared.


- Module/Class Scope: Accessible within the entire module or class.
- Global Scope: Accessible from anywhere in the application.

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

The Name property of a control specifies its identifier in the code.

vb
TextBox1.Name = "txtUserName"

If Then ... Else

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

A loop that executes as long as a condition is true.

vb
Dim i As Integer = 0
Do While i < 10
Console.WriteLine(i)
i += 1
Loop

Select Case

A control flow statement that handles multiple conditions.

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

Consider the following code snippet:

```vb
Option Strict On

Dim strValue As String = "123"


Dim intValue As Integer

' 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

The compiler error message will be something like:

```
Option Strict On disallows implicit conversions from 'String' to 'Integer'.
```

Correct Approach

To correct this, you should perform an explicit conversion using `Integer.Parse` or


`Integer.TryParse`:

```vb
Option Strict On

Dim strValue As String = "123"


Dim intValue As Integer

' Explicit conversion using Integer.Parse


intValue = Integer.Parse(strValue)
```

Or, to handle potential conversion failures:

```vb
Option Strict On

Dim strValue As String = "123"


Dim intValue As Integer

' Explicit conversion using Integer.TryParse


If Integer.TryParse(strValue, intValue) Then
' Conversion succeeded, intValue now holds the integer value
Else
' Handle the case where the conversion failed
MessageBox.Show("Invalid input. Please enter a valid number.")
End If
```

Summary

When `Option Strict` is set to `On`:


- Attempting an implicit conversion from a `String` to an `Integer` will result in a compile-time
error.
- This behavior enforces explicit conversions, ensuring type safety and reducing the risk of
runtime errors due to invalid type conversions.

Using input boxes to accept user input write an appllication that prompts the user to enter their
score and display the corresponding grade.
Task:

1. Design the form


2. Add a button with text "Enter Score"
3. A label to display the user's grade

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

' Validate the input


If Integer.TryParse(input, score) Then
Dim grade As String = CalculateGrade(score)
lblGrade.Text = $"Your grade is: {grade}"
Else
MessageBox.Show("Please enter a valid score.")
End If
End Sub

Private Function CalculateGrade(score As Integer) As String


' Determine the grade based on the score
If score >= 90 Then
Return "A"
ElseIf score >= 80 Then
Return "B"
ElseIf score >= 70 Then
Return "C"
ElseIf score >= 60 Then
Return "D"
Else
Return "F"
End If
End Function
End Class

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.

Public Class Form1


Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
Try
' Retrieve the input from the TextBox
Dim input As String = txtInput.Text

' Attempt to convert the input to an integer (explicit conversion)


Dim number As Integer = Convert.ToInt32(input)

' Display the result


lblResult.Text = $"Converted number is: {number}"
Catch ex As FormatException
' Handle the case where the input is not a valid integer
MessageBox.Show("Please enter a valid integer.", "Conversion Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
' Handle any other unexpected exceptions
MessageBox.Show($"An unexpected error occurred: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class

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

1. Clarity and Maintainability:


- Self-Documenting Code: Declaring variables with meaningful names makes the code more
readable and easier to understand. For example, `Dim age As Integer` is clearer than `Dim x`.
- Ease of Maintenance: Well-named variables and appropriate data types help developers
understand the purpose of each variable, making it easier to maintain and update the code.

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`.

5. Scope and Lifetime Management:


- Control over Variable Scope: Declaring variables within the correct scope (e.g., local vs.
global) helps manage the accessibility and lifetime of the data. This reduces the risk of
unintended side effects and memory leaks.
- Garbage Collection: Proper variable declaration helps the garbage collector to manage
memory more effectively by knowing when variables are no longer needed.

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

' Retrieve and validate the input


If Integer.TryParse(txtAge.Text, age) AndAlso Decimal.TryParse(txtSalary.Text, salary)
Then
' Process the valid input
lblResult.Text = $"Age: {age}, Salary: {salary:C2}"
Else
MessageBox.Show("Please enter valid age and salary values.", "Input Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
End Class
```

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

Declaring variables and choosing appropriate data types is crucial for:


- Clarity and maintainability of code.
- Type safety and error prevention.
- Optimizing performance in terms of memory and processing.
- Ensuring data validation and integrity.
- Managing scope and lifetime of variables efficiently.

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.

Difference Between Implicit and Explicit Type Conversions

Implicit Type Conversion:


- Definition: Implicit conversions occur automatically by the compiler when it determines that the
conversion is safe and no data will be lost. This typically happens when converting from a
smaller data type to a larger data type.
- Example: Converting an `Integer` to a `Double`.

Explicit Type Conversion:


- Definition: Explicit conversions require the programmer to specify the conversion using a cast
operator or conversion function. This is necessary when there is potential for data loss or when
converting between incompatible types.
- Example: Converting a `String` to an `Integer` using `Convert.ToInt32`.

Examples

Implicit Conversion Example:


In this example, the conversion from `Integer` to `Double` is done automatically by the compiler.
```vb
Dim intVal As Integer = 10
Dim doubleVal As Double

' Implicit conversion from Integer to Double


doubleVal = intVal

Console.WriteLine($"Implicit Conversion: Integer {intVal} to Double {doubleVal}")


```

Explicit Conversion Example:


Here, we explicitly convert a `String` to an `Integer` using `Convert.ToInt32`.

```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
```

Combined Code Snippet Demonstrating Both Conversions

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

' Implicit conversion from Integer to Double


doubleVal = intVal
Console.WriteLine($"Implicit Conversion: Integer {intVal} to Double {doubleVal}")

' Explicit Conversion Example


Dim strVal As String = "123"
Dim intConvertedVal As Integer

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

' Example of failed explicit conversion


strVal = "ABC"
Try
' Attempting explicit conversion from invalid 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 for string 'ABC'")
End Try
End Sub
End Module
```

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.

3. Failed Explicit Conversion:


- An attempt to convert an invalid string ("ABC") to an integer demonstrates how exception
handling catches and reports the error.

This code can be run in a console application in Visual Studio to observe both types of
conversions and their behaviors.

You might also like