You are on page 1of 149

DAV INSTITUTE OF MANAGEMENT

VISUAL BASIC LAB FILE

BCA-Vth Sem
Lab file(Jan-2024)
Submitted to: Dr. Sarita Kaushik
Submitted by: Kaushik Mandal
Registration No. : 2111031161
BCA-Vth

1
INDEX
S.no. List of Programs Page No. Sign

1. WAP in VB to enter the age. If the age is greater than or equal to 18 4-7
, the message “You are eligible to vote “ should be displayed and if
it less than 18 ,then message “You are not eligible to vote “ should
be displayed.
2. WAP in VB to find the largest of two numbers. 8-12

3. WAP in VB to find the largest of three numbers. 13-17

4. WAP in VB to find the largest of three numbers. 18-22

5. WAP in VB to check whether a given number is Armstrong number 23-27


or not.
6. WAP in VB to print all the even numbers from 1 to 50 28-30

7. WAP in VB to print all the odd numbers in a given range. 31-34

8. WAP in VB to print all the odd numbers in a given range. 35-39

9. WAP in VB to print all the odd numbers in a given range. 40-45

10. WAP in VB to make a simple calculator(+,-,* and /).Take two 46-50


numbers from user and one operator. Depending upon the
operator entered ,the programs should calculate and display the
result.
11. WAP in VB to print table of a given number. 51-54

12. WAP in VB to print table of numbers in a given range. 55-58

13. WAP in VB to display the square of a given number until the user 59-62
inputs positive number.It should stop if any negative number is
entered.
14. WAP in VB to print Fibonacci series using a procedure. 63-67

15. WAP to find to add two numbers using a function. 68-71

16. WAP in VB to create a single dimension array of 10 elements. It 72-76


should display the elements in ascending order.
17. WAP in VB to find all the even numbers in single dimension array of 77-81
10 elements.
18. WAP in VB to find the minimum and maximum value in the array of 82-86
10 elements.
19. WAP in VB to create a 2-D array of 3x3. The program should display 87-90

2
in matrix form.
20. WAP in VB to print sum of each row, sum of each column, sum of 91-96
front diagonal and sum of back diagonal of a 3x3 array.
21. WAP in VB to create a dynamic array. 97-102

22. WAP in VB to change the background colour of the form. 103-105

23. WAP in VB to create a form that contains Label control, TextBox, 106-112
Check boxes, radio buttons and command buttons.
24. WAP in VB to create form with List Box .Add items in the list, delete 113-118
items in the list, display total number of items in the list.
25. WAP to create menu in VB. 119-125

26. WAP to create MDI form. 126-130

27. WAP to create and use picture box in VB 131-134

28. WAP to create horizontal scrollbar and a textbox in VB. The font 135-137
size of text box should increase and decrease according to the
scrollbar.
29. WAP in VB to create three vertical scrollbars(For RGB). The 138-142
background colour of the form should change according to the
three scrollbars.
30. WAP in VB to show and hide form. 143-146

3
Que-1 WAP in VB to enter the age. If the age is greater than
or equal to 18 , the message “You are eligible to vote “
should be displayed and if it less than 18 ,then message “You
are not eligible to vote “ should be displayed.-
Ans-The described program is a simple Windows Forms Application (WFA)
written in Visual Basic (VB) that determines a person's eligibility to vote
based on their age. Here's a description of the program's main components
and functionality:
1: User Interface (UI):
· The program consists of a graphical user interface (GUI) created using
Windows Forms.
It includes a TextBox (AgeTextBox) for users to input their age, a Button
(CheckEligibilityButton) to trigger the eligibility check, and a Label
(EligibilityLabel) to display the result.
2. Event Handling:
The program responds to a button click event. When the user clicks the
"Check Eligibility" button, the associated event handler
(CheckEligibilityButton_Click) is executed.
3. Data Input:
The program reads the age entered by the user from the TextBox
(AgeTextBox).
4. Input Validation:
It validates whether the entered value is a valid integer using Integer.TryParse.
If the input is a valid integer, the program proceeds to the next step.
If not, it displays an error message in the Label (EligibilityLabel).
5. Eligibility Check:
4
The program compares the entered age with a predefined voting age
threshold (18).
If the age is greater than or equal to 18, it displays the message "You are
eligible to vote."
If the age is less than 18, it displays the message "You are not eligible to
vote."
6. User Feedback:
The result of the eligibility check is displayed in the Label (EligibilityLabel) on
the UI.
7. Error Handling:
If the entered value is not a valid integer, an error message is displayed,
guiding the user to enter a valid age.
8. End of Program:

The program ends after displaying the eligibility result or an error message.
In summary, this program provides a basic interactive way for users to input
their age, checks the validity of the input, and determines and communicates
their eligibility to vote based on a predefined age threshold. It serves as a
simple example of user input validation and conditional logic in a Windows
Forms Application.
Code:

Private Sub AgeTextBox_KeyDown(ByVal KeyCode As MSForms.ReturnInteger,


ByVal Shift As Integer)
' Check if the Enter key is pressed
If KeyCode = vbKeyReturn Then
' Trigger the CheckEligibilityButton_Click event
5
CheckEligibilityButton_Click
End If
End Sub

Private Sub CheckEligibilityButton_Click()


' Get the age entered by the user
Dim age As Integer
' Validate and convert the input to an integer
If IsNumeric(AgeTextBox.Text) Then
age = CInt(AgeTextBox.Text)
' Check eligibility based on age
If age >= 18 Then
EligibilityLabel.Caption = "You are eligible to vote."
Else
EligibilityLabel.Caption = "You are not eligible to vote."
End If
Else
' Display an error message if the input is not a valid number
EligibilityLabel.Caption = "Please enter a valid age."
End If
End Sub

6
Output-

7
Que-2: WAP in VB to find the largest of two numbers.
Ans- This algorithm outlines the logical steps to take user input, validate it,
compare the numbers, and display the result in order to find the largest of
two numbers in a Visual Basic program.
Algorithm:
1. Start:
- The program begins.
2. Input:
- Prompt the user to enter the first number.
- Read and store the entered value as `num1`.
3. Input Validation:
- Check if the entered value for `num1` is a valid number.
- If valid, proceed to the next step.
- If not valid, display an error message and end the program.
4. Input:
- Prompt the user to enter the second number.
- Read and store the entered value as `num2`.
5. Input Validation:
- Check if the entered value for `num2` is a valid number.
- If valid, proceed to the next step.
- If not valid, display an error message and end the program.
6. Comparison:

8
- Compare `num1` and `num2` to find the largest number.
- If `num1` is greater than `num2`, set `result` to `num1`.
- If `num2` is greater than or equal to `num1`, set `result` to `num2`.
7. Output:
- Display the result, indicating the largest number to the user.
8. End:
- The program ends.

Code for the above program:


Private Sub Number1TextBox_KeyDown(ByVal KeyCode As
MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
FindLargestButton_Click
End If
End Sub

Private Sub Number2TextBox_KeyDown(ByVal KeyCode As


MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
FindLargestButton_Click
End If
9
End Sub

Private Sub FindLargestButton_Click()


' Get the numbers entered by the user
Dim number1 As Double
Dim number2 As Double

' Validate and convert the input to numbers


If IsNumeric(Number1textBox.Text) And IsNumeric(Number2TextBox.Text)
Then
number1 = CDbl(Number1textBox.Text)
number2 = CDbl(Number2TextBox.Text)

' Find the largest number


Dim result As Double
If number1 > number2 Then
result = number1
Else
result = number2
End If

' Display the result

10
ResultLabel.Caption = "The largest number is: " & result
Else
' Display an error message if the input is not valid numbers
ResultLabel.Caption = "Please enter valid numbers."
End If
End Sub

11
Output:

12
Que-3: WAP in VB to find the largest of three numbers.
Ans- Algorithm for finding the largest of three numbers:
Algorithm:
1. Start:
- The program begins.
2. Input:
- Prompt the user to enter the first number and store it in `num1`.
- Prompt the user to enter the second number and store it in `num2`.
- Prompt the user to enter the third number and store it in `num3`.
3. Input Validation:
- Check if `num1`, `num2`, and `num3` are valid numeric values.
- If valid, proceed to the next step.
- If not valid, display an error message and end the program.
4. Comparison:
- Compare the three numbers to find the largest.
- If `num1` is greater than or equal to `num2` and `num1` is greater than or
equal to `num3`, set `largest` to `num1`.
- If `num2` is greater than or equal to `num1` and `num2` is greater than or
equal to `num3`, set `largest` to `num2`.
- If `num3` is greater than or equal to `num1` and `num3` is greater than or
equal to `num2`, set `largest` to `num3`.
5. Output:
13
- Display the result, indicating the largest number to the user.
6. End:
- The program ends.
This algorithm outlines the logical steps to take user input, validate it,
compare the numbers, and display the largest of three numbers in a program.

Code:
Private Sub Number1TextBox_KeyDown(ByVal KeyCode As
MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
FindLargestButton_Click
End If
End Sub

Private Sub Number2TextBox_KeyDown(ByVal KeyCode As


MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
FindLargestButton_Click
End If
End Sub

Private Sub Number3TextBox_KeyDown(ByVal KeyCode As


MSForms.ReturnInteger, ByVal Shift As Integer)

14
If KeyCode = vbKeyReturn Then
FindLargestButton_Click
End If
End Sub
Private Sub FindLargestButton_Click()

' Get the numbers entered by the user


Dim num1 As Double
Dim num2 As Double
Dim num3 As Double
' Validate and convert the input to doubles
If IsNumeric(Number1textBox.Text) And IsNumeric(Number2TextBox.Text)
And IsNumeric(Number3TextBox.Text) Then
num1 = CDbl(Number1textBox.Text)
num2 = CDbl(Number2TextBox.Text)
num3 = CDbl(Number3TextBox.Text)
' Find the largest number using a formula
Dim largest As Double
If num1 >= num2 And num1 >= num3 Then
largest = num1
ElseIf num2 >= num1 And num2 >= num3 Then
largest = num2

15
ElseIf num3 >= num1 And num3 >= num2 Then
largest = num3
End If
' Display the result
ResultLabel.Caption = "The largest number is: " & largest
Else
' Display an error message if any input is not a valid number
ResultLabel.Caption = "Please enter valid numbers for all three inputs."
End If
End Sub

16
Output:

This program prompts the user to enter three numbers, compares them, and
then prints the largest one.

17
Que-4: WAP in VB to check whether a given number is prime
or not.
Ans- The algorithm used to check whether a given number is prime involves
iterating through the potential divisors of the number. Here's a step-by-step
explanation:

1. User Input:
- The user inputs a number to be checked for primality.

2. Validation:
- The program validates the user input to ensure it is a valid integer. If not,
an error message is displayed.

3. Prime Checking Logic:


- If the input is a valid integer, the program proceeds to check whether the
number is prime.

4. Prime Initialization:
- The variable `isPrime` is initially set to `True`.

5. Base Cases:
- If the number is less than 2, it is not considered prime, and `isPrime` is set
to `False`.

18
6. Loop through Potential Divisors:
- A loop starts from 2 and goes up to the square root of the input number.
- For each iteration, it checks if the number is divisible by the current divisor
(`i`).
- If a divisor is found, the number is not prime, and `isPrime` is set to
`False`. The loop is exited using `Exit For`.

7. Display Result:
- Based on the value of `isPrime`, the program displays whether the input
number is a prime number or not.

In summary, a number is considered prime if it has no divisors other than 1


and itself. The algorithm optimizes the search for divisors by only checking up
to the square root of the number, as any factor larger than the square root
would have a corresponding factor smaller than the square root. This helps
improve the efficiency of the algorithm.

The code combines this logic with user interface handling to create a simple
prime checking application in Visual Basic (VBA).

Code:-
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)
' Check if the Enter key is pressed
19
If KeyCode = vbKeyReturn Then
' Trigger the Button1_Click event
Button1_Click
End If
End Sub

Private Sub Button1_Click()


' Validate user input
Dim number As Integer

On Error Resume Next


number = Val(TextBox1.Text)
On Error GoTo 0

' Check if the number is prime


Dim isPrime As Boolean
isPrime = True

If number < 2 Then


isPrime = False
Else
For i = 2 To Sqr(number)

20
If number Mod i = 0 Then
isPrime = False
Exit For
End If
Next
End If

' Displaying the result


If isPrime Then
Label1.Caption = number & " is a prime number."
Else
Label1.Caption = number & " is not a prime number."
End If
End Sub

21
Output:

22
Que-5: WAP in VB to check whether a given number is
Armstrong number or not.
Ans- To check whether a given number is an Armstrong number (also known
as a narcissistic number or pluperfect digit), you can use the following
algorithm:

1. User Input:
- The user inputs a number to be checked for being an Armstrong number.

2. Validation:
- Validate the user input to ensure it is a valid integer. If not, display an error
message.

3. Armstrong Checking Logic:


- If the input is a valid integer, proceed to check whether the number is an
Armstrong number.

4. Calculate Sum of Digits Raised to the Power of the Number of Digits:


- Find the total sum of each digit raised to the power of the number of
digits in the number.

5. Compare with the Original Number:


- If the calculated sum is equal to the original number, then the number is
an Armstrong number.
23
6. Display Result:
- Based on the result, display whether the input number is an Armstrong
number or not.

Code :
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)
' Check if the Enter key is pressed
If KeyCode = vbKeyReturn Then
' Trigger the Button1_Click event
Button1_Click
End If
End Sub
Private Sub Button1_Click()
' Validate user input
Dim number As Integer
On Error Resume Next
number = Val(TextBox1.Text)
On Error GoTo 0
' Check if the number is an Armstrong number
Dim originalNumber As Integer
Dim sum As Integer
24
Dim temp As Integer
Dim digitCount As Integer
If number >= 0 Then
' Store the original number for comparison later
originalNumber = number

' Count the number of digits in the input


Do While number > 0
number \= 10
digitCount = digitCount + 1
Loop
' Reset the number for further calculation
number = originalNumber
' Calculate the sum of each digit raised to the power of the digit count
Do While number > 0
temp = number Mod 10
sum = sum + temp ^ digitCount
number \= 10
Loop
' Display the result
If sum = originalNumber Then
Label1.Caption = originalNumber & " is an Armstrong number."

25
Else
Label1.Caption = originalNumber & " is not an Armstrong number."
End If
Else
Label1.Caption = "Not a valid input."
End If
End Sub
```

This code checks whether the input number is an Armstrong number and
displays the result .

26
Output :

27
Que-6: WAP in VB to print all the even numbers from 1 to
50.
Sol:
Algiorithm:-
1. Start: The beginning of the algorithm.
2. Initialize a loop variable i to 1: Create a variable named `i` and set its initial
value to 1. This variable will be used to iterate through the numbers.
3. Repeat the following steps until i reaches 50:
If i is even (i % 2 equals 0), then:
Step A- Check if the current value of `i` is even. This is done by using the
modulo operator `%`, which gives the remainder when `i` is divided by 2. If
the remainder is 0, then `i` is even.
- If `i` is even, then proceed to the next step.
- i. Print or display the value of i: Output or display the current value of `i`.

Step b. Increment i by 1: After processing the current value of `i`, increase


its value by 1 to move to the next number in the sequence.

4. End: The end of the algorithm.

This algorithm initializes a variable (`i`), iterates through numbers from 1 to


50, checks if each number is even, and if so, prints or displays that number.
The process continues until `i` reaches 50, at which point the algorithm ends.

28
This algorithm is designed to find and display all even numbers in the range
from 1 to 50.

Code-
Public Class Form1
Private Sub btnPrintEvenNumbers_Click(sender As Object, e As EventArgs)
Handles btnPrintEvenNumbers.Click
' Clear any previous output
txtOutput.Text = ""
' Loop through numbers from 1 to 50
For i As Integer = 1 To 50
' Check if the number is even
If i Mod 2 = 0 Then
' Append the even number to the output textbox
txtOutput.AppendText(i.ToString() & Environment.NewLine)
End If
Next
End Sub
End Class

29
Output:

30
Que-7: WAP in VB to print all the odd numbers in a given range.
Ans: Algorithm:
Certainly! Here's a basic algorithm for a Visual Basic .NET program that takes a
range from the user and displays all odd numbers in that range using a Windows
Forms Application:

Start:

Initialize the Windows Form application.


Create a Form with TextBox controls for start and end range inputs, a Button
control to trigger the action, and an event handler for the button click.
User Input:

When the user clicks the button:


Read the values entered in the start and end range TextBox controls.
Validate the input to ensure that valid integers are provided.
Print Odd Numbers:

If the input is valid:


Call a subroutine (e.g., PrintOddNumbers) with the start and end range as
parameters.
Odd Number Subroutine (PrintOddNumbers):

Validate the range:

31
If the start range is greater than the end range, show an error message and return.
Loop through the range:
For each number in the range, check if it's odd (use the modulus operator).
If it's odd, add it to a string or a collection for display.
Display Results:

If there are odd numbers to display:


Display the odd numbers, possibly in a MessageBox or another form of output.
End:
End the program.

Code:-
Public Class Form1
Private Sub btnPrintOddNumbers_Click(sender As Object, e As EventArgs)
Handles btnPrintOddNumbers.Click
' Get the range from the user
Dim startRange As Integer
Dim endRange As Integer
If Integer.TryParse(txtStartRange.Text, startRange) AndAlso
Integer.TryParse(txtEndRange.Text, endRange) Then
' Call the function to print odd numbers
PrintOddNumbers(startRange, endRange)
Else

32
MessageBox.Show("Invalid input. Please enter valid integers for the
range.")
End If
End Sub
Sub PrintOddNumbers(startRange As Integer, endRange As Integer)
' Validate the range
If startRange > endRange Then
MessageBox.Show("Invalid range. Start of the range should be less
than or equal to the end of the range.")
Return
End If
' Display odd numbers in the range in a MessageBox
Dim result As String = $"Odd numbers in the range {startRange} to
{endRange}:" & Environment.NewLine
For i As Integer = startRange To endRange
If i Mod 2 <> 0 Then
result &= i & " "
End If
Next

MessageBox.Show(result, "Odd Numbers")


End Sub
End Class

33
Output:

34
Que- 8. WAP in VB to find all the prime numbers in a given
range.
Ans:
Algorithm:-
Here's a basic algorithm for a Visual Basic .NET program that takes a range
from the user and displays all prime numbers in that range using a Windows
Forms Application:
Start:
Initialize the Windows Form application.
Create a Form with TextBox controls for start and end range inputs, a Button
control to trigger the action, and an event handler for the button click.
User Input:
When the user clicks the button:
Read the values entered in the start and end range TextBox controls.
Validate the input to ensure that valid integers are provided.
Find Prime Numbers Subroutine (FindPrimes):
If the input is valid:
Call a subroutine (FindPrimes) with the start and end range as parameters.
Prime Number Checking Function (IsPrime):
Create a function (IsPrime) that checks if a given number is prime.
If the number is less than 2, return false.
Iterate from 2 to the square root of the number.

35
If the number is divisible by any value in this range, return false.
Otherwise, return true.
Display Results:
If there are prime numbers to display:
Display the prime numbers, possibly in a MessageBox or another form of
output.
End:
End the program.

Code:-
Public Class Form1
Private Sub btnFindPrimes_Click(sender As Object, e As EventArgs) Handles
btnFindPrimes.Click
' Get the range from the user
Dim startRange As Integer
Dim endRange As Integer

If Integer.TryParse(txtStartRange.Text, startRange) AndAlso


Integer.TryParse(txtEndRange.Text, endRange) Then
' Call the function to find prime numbers
FindPrimes(startRange, endRange)
Else
MessageBox.Show("Invalid input. Please enter valid integers for the
range.")

36
End If
End Sub
Sub FindPrimes(startRange As Integer, endRange As Integer)
' Validate the range
If startRange > endRange Then
MessageBox.Show("Invalid range. Start of the range should be less
than or equal to the end of the range.")
Return
End If
' Display prime numbers in the range in a MessageBox
Dim result As String = $"Prime numbers in the range {startRange} to
{endRange}:" & Environment.NewLine
For i As Integer = startRange To endRange
If IsPrime(i) Then
result &= i & " "
End If
Next
If result.Length = 0 Then
result = "No prime numbers found in the given range."
End If
MessageBox.Show(result, "Prime Numbers")
End Sub

37
Function IsPrime(number As Integer) As Boolean
If number < 2 Then
Return False
End If
For i As Integer = 2 To Math.Sqrt(number)
If number Mod i = 0 Then
Return False
End If
Next
Return True
End Function
End Class

38
Output:-

39
Que-9:- WAP in VB to find all the Armstrong numbers in a
given range.
Ans-
Algorithm:-
Here's a basic algorithm for a Visual Basic .NET program that takes a range
from the user and displays all Armstrong numbers in that range using a
Windows Forms Application:

Start:

Initialize the Windows Form application.


Create a Form with TextBox controls for start and end range inputs, a Button
control to trigger the action, and an event handler for the button click.
User Input:

When the user clicks the button:


Read the values entered in the start and end range TextBox controls.
Validate the input to ensure that valid integers are provided.
Find Armstrong Numbers Subroutine (FindArmstrongNumbers):

If the input is valid:


Call a subroutine (FindArmstrongNumbers) with the start and end range as
parameters.
40
Armstrong Number Checking Function (IsArmstrongNumber):

Create a function (IsArmstrongNumber) that checks if a given number is an


Armstrong number.
Initialize a variable to store the original number.
Calculate the power, which is the number of digits in the number.
Iterate through the digits of the number, raising each digit to the power and
accumulating the result.
Check if the accumulated result is equal to the original number.
Display Results:

If there are Armstrong numbers to display:


Display the Armstrong numbers, possibly in a MessageBox or another form of
output.
End:

End the program.

Code:-
Public Class Form1
Private Sub btnFindArmstrong_Click(sender As Object, e As EventArgs)
Handles btnFindArmstrong.Click
' Get the range from the user
Dim startRange As Integer

41
Dim endRange As Integer

If Integer.TryParse(txtStartRange.Text, startRange) AndAlso


Integer.TryParse(txtEndRange.Text, endRange) Then
' Call the function to find Armstrong numbers
FindArmstrongNumbers(startRange, endRange)
Else
MessageBox.Show("Invalid input. Please enter valid integers for the
range.")
End If
End Sub

Sub FindArmstrongNumbers(startRange As Integer, endRange As Integer)


' Validate the range
If startRange > endRange Then
MessageBox.Show("Invalid range. Start of the range should be less
than or equal to the end of the range.")
Return
End If

' Display Armstrong numbers in the range in a MessageBox


Dim result As String = $"Armstrong numbers in the range {startRange} to
{endRange}:" & Environment.NewLine

42
For i As Integer = startRange To endRange
If IsArmstrongNumber(i) Then
result &= i & " "
End If
Next

If result.Length = 0 Then
result = "No Armstrong numbers found in the given range."
End If

MessageBox.Show(result, "Armstrong Numbers")


End Sub

Function IsArmstrongNumber(number As Integer) As Boolean


Dim originalNumber As Integer = number
Dim result As Integer = 0
Dim power As Integer = Math.Floor(Math.Log10(number) + 1)

While number > 0


Dim digit As Integer = number Mod 10
result += CInt(Math.Pow(digit, power))

43
number \= 10
End While

Return result = originalNumber


End Function
End Class

44
Output:-

45
Que 10:- WAP in VB to make a simple calculator(+,-,*
and /).Take two numbers from user and one operator.
Depending upon the operator entered ,the programs should
calculate
and display the result.
Ans:- Here’s a basic algorithm for a Visual Basic .NET program that creates a
simple calculator (addition, subtraction, multiplication, and division) with two
numbers taken from the user and one operator:
Start:

Initialize the Windows Form application.


Create a Form with TextBox controls for the two numbers (txtNum1 and
txtNum2), a TextBox control for the operator (txtOperator), a Button control
(btnCalculate), and an event handler for the button click.
User Input:

When the user clicks the button:


Read the values entered in txtNum1, txtNum2, and txtOperator.
Validate the input to ensure that valid numbers are provided for calculation.
Perform Calculation:

If the input is valid:


Convert the input numbers to numeric values (e.g., Double).

46
Use a Select Case or If-Else statement to perform the calculation based on
the operator entered.
Handle division by zero to avoid errors.
Display Result:

Display the result of the calculation in a MessageBox or another form of


output.
End:

End the program.

Code:-
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles
btnCalculate.Click
‘ Get the numbers and operator from the user
Dim num1 As Double
Dim num2 As Double
Dim [operator] As String = txtOperator.Text

If Double.TryParse(txtNum1.Text, num1) AndAlso


Double.TryParse(txtNum2.Text, num2) Then
‘ Perform the calculation based on the operator
Dim result As Double

47
Select Case [operator]
Case “+”
result = num1 + num2
Case “-“
result = num1 – num2
Case “*”
result = num1 * num2
Case “/”
If num2 <> 0 Then
result = num1 / num2
Else
MessageBox.Show(“Cannot divide by zero. Please enter a non-
zero value for the second number.”)
Return
End If
Case Else
MessageBox.Show(“Invalid operator. Please enter a valid operator
(+, -, *, /).”)
Return
End Select

‘ Display the result


48
MessageBox.Show($”Result: {result}”, “Calculator Result”)
Else
MessageBox.Show(“Invalid input. Please enter valid numbers for
calculation.”)
End If
End Sub
End Class

49
Output:-

50
Que-11:- WAP in VB to print table of a given number.
Ans:-
Algorithm:
Here's a basic algorithm for a Visual Basic .NET program that prints the table
of a given number using a Windows Forms Application:

Start:
Initialize the Windows Form application.
Create a Form with a TextBox control for the input number (txtNumber), a
Button control to trigger the action (btnPrintTable), and an event handler for
the button click.
User Input:
When the user clicks the button:
Read the value entered in txtNumber.
Validate the input to ensure that a valid integer is provided.
Print Table Subroutine (PrintTable):

If the input is valid:


Call a subroutine (PrintTable) with the input number as a parameter.
Display Table:

In the PrintTable subroutine:

51
Display the multiplication table of the given number up to a specified range
(e.g., up to 10) in a MessageBox or another form of output.
End:
End the program.

Code:-
Public Class Form1
Private Sub btnPrintTable_Click(sender As Object, e As EventArgs) Handles
btnPrintTable.Click
' Get the number from the user
Dim inputNumber As Integer

If Integer.TryParse(txtNumber.Text, inputNumber) Then


' Call the function to print the table
PrintTable(inputNumber)
Else
MessageBox.Show("Invalid input. Please enter a valid integer.")
End If
End Sub

Sub PrintTable(number As Integer)


' Display the table in a MessageBox or another form of output

52
Dim result As String = $"Table of {number}:" & Environment.NewLine

For i As Integer = 1 To 10
Dim product As Integer = number * i
result &= $"{number} x {i} = {product}" & Environment.NewLine
Next

MessageBox.Show(result, "Multiplication Table")


End Sub
End Class

53
Output:-

54
Que-12:- WAP in VB to print table of numbers in a given
range.
Ans:
Algorithm:-
Here's a basic algorithm for a Visual Basic .NET program that takes a range
from the user and prints the multiplication tables for each number within
that range using a Windows Forms Application:

Start:
Initialize the Windows Form application.
Create a Form with TextBox controls for the starting and ending numbers of
the range (txtStartRange and txtEndRange), a Button control to trigger the
action (btnPrintTables), and an event handler for the button click.
User Input:
When the user clicks the button:
Read the values entered in txtStartRange and txtEndRange.
Validate the input to ensure that valid integers are provided for the range.
Print Tables Subroutine (PrintTables):

If the input is valid:


Call a subroutine (PrintTables) with the starting and ending numbers as
parameters.
Display Tables:

55
In the PrintTables subroutine:
Loop through each number in the specified range.
For each number, loop through the range from 1 to 10 to calculate and
display the multiplication table.
End:

End the program.

Code:-
Public Class Form1
Private Sub btnPrintTables_Click(sender As Object, e As EventArgs) Handles
btnPrintTables.Click
' Get the range from the user
Dim startRange As Integer
Dim endRange As Integer

If Integer.TryParse(txtStartRange.Text, startRange) AndAlso


Integer.TryParse(txtEndRange.Text, endRange) Then
' Call the function to print tables
PrintTables(startRange, endRange)
Else
MessageBox.Show("Invalid input. Please enter valid integers for the
range.")

56
End If
End Sub

Sub PrintTables(startRange As Integer, endRange As Integer)


' Display the tables in a MessageBox or another form of output
Dim result As String = ""

For i As Integer = startRange To endRange


result &= $"Table of {i}:" & Environment.NewLine
For j As Integer = 1 To 10
result &= $"{i} x {j} = {i * j}" & Environment.NewLine
Next
result &= Environment.NewLine
Next

MessageBox.Show(result, "Multiplication Tables")


End Sub
End Class

57
Output:-

58
Que-13: WAP in VB to display the square of a given number
until the user inputs positive number.It should stop if any
negative number is entered.
Ans:
Algorithm:
Here's a basic algorithm for a Visual Basic .NET program that displays the
square of a given number until a negative number is entered:

Start:
Initialize the Windows Form application.
Create a Form with a TextBox control for the number input (txtNumber), a
Button control to trigger the action (btnCalculate), and an event handler for
the button click.

User Input:
When the user clicks the button:
Read the value entered in txtNumber.
Validate the input to ensure that a valid integer is provided.

Check for Positivity:


If the input is valid:
Check if the entered number is non-negative (greater than or equal to 0).
Calculate and Display Square:
59
If the number is non-negative:
Calculate the square of the number.
Display the square in a MessageBox or another form of output.
Stop on Negative Input:
If a negative number is entered:
Display a message indicating that a negative number has been entered.
Stop the program.
End:

End the program.


Code:-
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles
btnCalculate.Click
Do
Dim inputNumber As Integer

' Get the number from the user


If Integer.TryParse(txtNumber.Text, inputNumber) Then
' Check if the number is positive
If inputNumber >= 0 Then
' Display the square of the number

60
Dim square As Integer = inputNumber * inputNumber
MessageBox.Show($"Square of {inputNumber} is {square}",
"Square Calculation")
Else
' If a negative number is entered, stop the program
MessageBox.Show("Negative number entered. Stopping the
program.", "Program Stopped")
Exit Do ' Exit the loop
End If
Else
' Invalid input
MessageBox.Show("Invalid input. Please enter a valid integer.",
"Error")
Exit Do ' Exit the loop
End If
Loop While True
End Sub
End Class

61
Output:-

62
Que-14: WAP in VB to print Fibonacci series using a
procedure.
Ans:
Algorithm:Here is a an algorithm to print Fibonacci series using a
procedure.
Start:

Open a new Windows Forms Application in Visual Studio.


Design the Form:

Add a TextBox named txtLimit for user input.


Add a Button named btnGenerate to trigger the Fibonacci series generation.
Add a multiline TextBox named TextBox1 to display the result.
Define Fibonacci Function:

Create a private function named Fibonacci that takes an integer parameter n


and returns an integer.
Implement the Fibonacci logic using recursion.
Define PrintFibonacciSeries Procedure:

63
Create a private procedure named PrintFibonacciSeries that takes an integer
parameter limit.
Inside the procedure, use a loop to iterate from 0 to limit - 1.
Call the Fibonacci function for each iteration and append the result to a
string.
Set the multiline TextBox's text property to the generated string.
Handle Button Click Event:

Create an event handler for the btnGenerate button click event named
btnGenerate_Click.
Inside the event handler, validate the input from txtLimit.
If the input is a valid integer, call the PrintFibonacciSeries procedure with the
entered limit.
Run the Application:

Run the application and enter a valid integer in the txtLimit TextBox.
Click the btnGenerate button to display the Fibonacci series in the TextBox1.

Code:-
Public Class FibonacciForm

' Function to calculate Fibonacci series


Private Function Fibonacci(n As Integer) As Integer

64
If n <= 1 Then
Return n
Else
Return Fibonacci(n - 1) + Fibonacci(n - 2)
End If
End Function

' Procedure to print Fibonacci series up to a given number


Private Sub PrintFibonacciSeries(limit As Integer)
Console.WriteLine("Fibonacci Series up to " & limit & " terms:")

For i As Integer = 0 To limit - 1


Console.Write(Fibonacci(i) & " ")
Next i

Console.WriteLine()
End Sub

' Event handler for the form load event


Private Sub FibonacciForm_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
' Change the number inside PrintFibonacciSeries to print a different
number of terms
65
PrintFibonacciSeries(10)
End Sub

End Class

66
Output:-

67
Que-15: WAP to find to add two numbers using a function.
Ans:-
Algorithm: Here is the algorithm for adding two numbers using a function
in a Visual Basic form:

Start:
Initialize the form with textboxes for input (txtNum1 and txtNum2), a button
(btnAdd), and a label (lblResult).
Create a function named AddNumbers that takes two parameters (num1 and
num2) and returns the sum.

User Input:
User enters a numeric value in txtNum1 and txtNum2.
Add Button Click:
When the user clicks the "Add" button (btnAdd):
Retrieve the numeric values from txtNum1 and txtNum2.
Call the AddNumbers function with the entered values.
Display the result in lblResult.

AddNumbers Function:
Define the function AddNumbers:
Takes two parameters (num1 and num2).

68
Returns the sum of num1 and num2.

Display Result:
Show the result in the lblResult label.
End:

End the algorithm.

Code :
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
' Get the numbers from the textboxes
Dim num1 As Double = CDbl(txtNum1.Text)
Dim num2 As Double = CDbl(txtNum2.Text)

' Call the AddNumbers function and display the result


Dim result As Double = AddNumbers(num1, num2)
lblResult.Text = "Result: " & result.ToString()
End Sub

' Function to add two numbers

69
Private Function AddNumbers(ByVal num1 As Double, ByVal num2 As
Double) As Double
Return num1 + num2
End Function
End Class

70
Output:

71
Que-16: WAP in VB to create a single dimension array of 10
elements. It should display the elements in ascending order.
Ans-
Algorithm:-
Here's a step-by-step explanation / algorithm:

Array Declaration:

Declare an array named myArray with 10 elements. The indices of the array
range from 0 to 9.
Form Load Event:

When the form is loaded, the Form1_Load event is triggered.


It calls the FillAndDisplayArray method.
FillAndDisplayArray Method:

This method is responsible for filling the array with values and displaying the
sorted array.
It uses a For loop to iterate 10 times, asking the user to enter values for each
array element using InputBox.
The entered values are converted to integers using CInt and stored in the
array.
The array is then sorted in ascending order using Array.Sort.
72
The sorted array is displayed in a MessageBox with each element separated
by spaces.
User Interaction:

The user interacts with the program by entering values when prompted by
the InputBox.
MessageBox Display:

After the user has entered all values, the sorted array is displayed in a
MessageBox with a title "Sorted Array."

Code:-
Public Class Form1
' Declare an array to store 10 elements
Dim myArray(9) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Call the function to fill and display the array
FillAndDisplayArray()
End Sub

Private Sub FillAndDisplayArray()

73
' Fill the array with user input or random values
For i As Integer = 0 To 9
' You can replace the InputBox with any method to get values from the
user
myArray(i) = CInt(InputBox("Enter element " & (i + 1)))
Next

' Sort the array in ascending order


Array.Sort(myArray)

' Display the sorted array in a MessageBox


Dim message As String = "Sorted Array: " & vbCrLf
For Each element As Integer In myArray
message &= element.ToString() & " "
Next

MessageBox.Show(message, "Sorted Array", MessageBoxButtons.OK,


MessageBoxIcon.Information)
End Sub
End Class

74
Output:-

A simple form with a


command button to run
program.

This is an input box opens


10 times to take input for an
array.
Inputted:
{42,95,75,23,11,87,46,81,93
,50}

75
Message box
Displaying output.

76
Que:17 WAP in VB to find all the even numbers in single
dimension array of 10 elements.
Ans:
Algorithm:
Here's the algorithm to find all the even numbers in single dimension array of
10 elements.

Array Declaration:

Declare an integer array named myArray with 10 elements.


Form Load Event:

When the form is loaded:


Call the FillAndDisplayEvenNumbers method.
FillAndDisplayEvenNumbers Method:

Use a loop to fill myArray with user input obtained through an InputBox.
Create a list named evenNumbers to store even integers.
Iterate through each element in myArray:
Check if the element is even (divisible by 2).
If even, add it to the evenNumbers list.
Display the even numbers in a MessageBox.

77
User Interaction:

The user interacts by entering values when prompted by the InputBox.


MessageBox Display:

After the user enters values, even numbers are identified and displayed in a
MessageBox.
This algorithm outlines the steps for filling an array with user input, finding
even numbers, and displaying the even numbers in a MessageBox.

Code:
Public Class Form1
' Declare an array to store 10 elements
Dim myArray(9) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Call the function to fill and display the array
FillAndDisplayEvenNumbers()
End Sub

Private Sub FillAndDisplayEvenNumbers()


' Fill the array with user input or random values

78
For i As Integer = 0 To 9
' You can replace the InputBox with any method to get values from the
user
myArray(i) = CInt(InputBox("Enter element " & (i + 1)))
Next

' Find and display even numbers in the array


Dim evenNumbers As New List(Of Integer)
For Each num As Integer In myArray
If num Mod 2 = 0 Then
evenNumbers.Add(num)
End If
Next

' Display even numbers in a MessageBox


Dim message As String = "Even Numbers: " & vbCrLf
For Each evenNum As Integer In evenNumbers
message &= evenNum.ToString() & " "
Next
MessageBox.Show(message, "Even Numbers", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub
End Class
79
Output:-

A simple form with a


command button to run
program.

This is an input box opens


10 times to take input for an
array.
Inputted: {37, 14, 83, 50, 9,
72, 64, 21, 95, 6}

80
Message box
Displaying
output.

81
Que-18: WAP in VB to find the minimum and maximum
value in the array of 10 elements.
Ans:-
Algorithm:-
Here's the algorithm in plain text for finding the minimum and maximum
values in an array of 10 elements:

Array Declaration:

Declare an integer array named myArray with 10 elements.


Form Load Event:

When the form is loaded:


Call the FillAndDisplayMinMax method.
FillAndDisplayMinMax Method:

Use a loop to fill myArray with user input obtained through an InputBox.
Find the minimum value in the array using the Min function.
Find the maximum value in the array using the Max function.
Display the minimum and maximum values in a MessageBox.
User Interaction:

82
The user interacts by entering values when prompted by the InputBox.
MessageBox Display:

After the user enters values, the program identifies and displays the
minimum and maximum values in a MessageBox.
This algorithm outlines the steps for filling an array with user input, finding
the minimum and maximum values, and displaying them in a MessageBox.

Code:
Public Class Form1
' Declare an array to store 10 elements
Dim myArray(9) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Call the function to fill and display the array
FillAndDisplayMinMax()
End Sub

Private Sub FillAndDisplayMinMax()


' Fill the array with user input or random values
For i As Integer = 0 To 9

83
' You can replace the InputBox with any method to get values from the
user
myArray(i) = CInt(InputBox("Enter element " & (i + 1)))
Next

' Find the minimum and maximum values in the array


Dim minValue As Integer = myArray.Min()
Dim maxValue As Integer = myArray.Max()

' Display the minimum and maximum values in a MessageBox


Dim message As String = $"Minimum Value: {minValue}
{vbCrLf}Maximum Value: {maxValue}"

MessageBox.Show(message, "Min and Max Values",


MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class

84
Output:

A simple program
with a command
button to run it.

This is an input box opens


10 times to take input for an
array.
Inputted: {37, 14, 83, 50, 9,
72, 64, 21, 95, 6}

85
Message box
Displaying
output.

86
Que-19: WAP in VB to create a 2-D array of 3x3. The program
should display in matrix form.
Ans:
Algorithm:
Algorithm to find the minimum and maximum values in a 2D array (matrix) .

Matrix Declaration:
Declare a 2D array (matrix) of size 3x3 to store integers.
User Input or Initialization:

Optionally, obtain values for each element in the matrix, either through user
input or initialization.
Initialize Minimum and Maximum:

Set two variables, minValue and maxValue, to the first element of the matrix
(matrix[0][0]).
Iterate Through Matrix:

Use nested loops to iterate through each element in the matrix.


For each element:
If the element is less than minValue, update minValue.
If the element is greater than maxValue, update maxValue.

87
Display Results:

The final minValue and maxValue represent the minimum and maximum
values in the matrix.
This algorithm outlines the steps to find the minimum and maximum values
in a 2D array (matrix) without providing specific code.

Code: Public Class Form1


' Declare a 2-D array of size 3x3
Dim matrix(2, 2) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Call the function to fill and display the matrix
FillAndDisplayMatrix()
End Sub

Private Sub FillAndDisplayMatrix()


' Fill the matrix with sample values (you can modify this part as needed)
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(0, 2) = 3
matrix(1, 0) = 4

88
matrix(1, 1) = 5
matrix(1, 2) = 6
matrix(2, 0) = 7
matrix(2, 1) = 8
matrix(2, 2) = 9

' Display the matrix in a MessageBox


Dim message As String = "Matrix Form:" & vbCrLf
For i As Integer = 0 To 2
For j As Integer = 0 To 2
message &= matrix(i, j).ToString() & " "
Next
message &= vbCrLf
Next

lblResult.Text =message, " ",


End Sub
End Class

89
Output:

90
Que-20: WAP in VB to print sum of each row, sum of each
column, sum of front diagonal and sum of back diagonal of a
3x3 array.
Ans:
Algorithm: Algorithm for calculating the sum of each row, each column,
the sum of the front diagonal, and the sum of the back diagonal of a 3x3
array:

Initialize the 3x3 array:

Create a 2D array (matrix) with dimensions 3x3.


Input values into the array:

Use a loop to prompt the user to input values for each element of the matrix.
Display the original matrix:

Use a loop to display the elements of the matrix on the console or form.
Calculate and display the sum of each row:

Use nested loops to iterate through each row and calculate the sum of the
elements in each row.
Display the sum of each row.
Calculate and display the sum of each column:
91
Use nested loops to iterate through each column and calculate the sum of
the elements in each column.
Display the sum of each column.
Calculate and display the sum of the front diagonal:

Use a loop to iterate through the elements on the front diagonal (i.e.,
elements at [0,0], [1,1], [2,2]) and calculate their sum.
Display the sum of the front diagonal.
Calculate and display the sum of the back diagonal:

Use a loop to iterate through the elements on the back diagonal (i.e.,
elements at [0,2], [1,1], [2,0]) and calculate their sum.
Display the sum of the back diagonal.
End of algorithm.

This algorithm outlines the steps to achieve the desired calculations for a 3x3
array. You can implement these steps in your preferred programming
language, such as Visual Basic (VB), following the logic provided in the
previous code examples.

Code:
Public Class Form1

92
Dim matrix(2, 2) As Integer

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles


btnCalculate.Click
' Input values into the array
For i As Integer = 0 To 2
For j As Integer = 0 To 2
matrix(i, j) = Integer.Parse(InputBox($"Enter element at position ({i +
1},{j + 1}):", "Input", "0"))
Next
Next

' Display the original matrix


DisplayMatrix(matrix)

' Calculate and display the sum of each row


lblResults.Text &= "Sum of Each Row:" & vbCrLf
For i As Integer = 0 To 2
Dim rowSum As Integer = 0
For j As Integer = 0 To 2
rowSum += matrix(i, j)
Next
lblResults.Text &= $"Row {i + 1}: {rowSum}" & vbCrLf
93
Next

' Calculate and display the sum of each column


lblResults.Text &= vbCrLf & "Sum of Each Column:" & vbCrLf
For j As Integer = 0 To 2
Dim colSum As Integer = 0
For i As Integer = 0 To 2
colSum += matrix(i, j)
Next
lblResults.Text &= $"Column {j + 1}: {colSum}" & vbCrLf
Next

' Calculate and display the sum of the front diagonal


Dim frontDiagonalSum As Integer = 0
For i As Integer = 0 To 2
frontDiagonalSum += matrix(i, i)
Next
lblResults.Text &= vbCrLf & $"Sum of Front Diagonal:
{frontDiagonalSum}" & vbCrLf

' Calculate and display the sum of the back diagonal


Dim backDiagonalSum As Integer = 0

94
For i As Integer = 0 To 2
backDiagonalSum += matrix(i, 2 - i)
Next
lblResults.Text &= vbCrLf & $"Sum of Back Diagonal: {backDiagonalSum}"
& vbCrLf
End Sub

' Helper method to display the matrix


Sub DisplayMatrix(matrix(,) As Integer)
lblResults.Text = "Original Matrix:" & vbCrLf
For i As Integer = 0 To 2
For j As Integer = 0 To 2
lblResults.Text &= matrix(i, j) & " "
Next
lblResults.Text &= vbCrLf
Next
End Sub
End Class

95
Output:

Input Box Use to


take input for
matrix elements

96
Que-21: WAP in VB to create a dynamic array.
Ans:
Algorithm:
Here's an algorithm describing the logic of the program to create a dynamic
array in vb.

Initialize:

Declare a dynamic array variable (dynamicArray) to store strings.


Form Load Event:

In the Form Load event:


Initialize the dynamic array with some initial values.
Display the initial array in a List Box on the form.
UpdateListBox Method:

Create a method (UpdateListBox) to update the List Box with the contents of
the dynamic array:
Clear the List Box.
Iterate through the dynamic array and add each item to the List Box.
Button Click Event (btnAddItem_Click):

97
In the button click event (triggered when a button is clicked to add a new
item):
Prompt the user for input using an input box.
Check if the user entered a value.
If a value is entered:
Resize the dynamic array to accommodate the new item (using ReDim
Preserve).
Assign the new item to the last index of the array.
Call the UpdateListBox method to refresh the List Box with the updated array.
This algorithm outlines the steps without providing specific code. The key
actions include initializing the array, updating the List Box, and adding a new
item based on user input. It allows for a clear understanding of the program's
logic and flow.

Code:
Public Class Form1
' Declare a dynamic array
Dim dynamicArray() As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Initialize the dynamic array with some values
ReDim dynamicArray(2)
dynamicArray(0) = "Item 1"
dynamicArray(1) = "Item 2"
98
dynamicArray(2) = "Item 3"

' Display the array in the List Box


UpdateListBox()
End Sub

' Helper method to update the List Box with the contents of the dynamic
array
Private Sub UpdateListBox()
ListBox1.Items.Clear()
For Each item In dynamicArray
ListBox1.Items.Add(item)
Next
End Sub

' Button click event to add a new item to the dynamic array using user
input
Private Sub btnAddItem_Click(sender As Object, e As EventArgs) Handles
btnAddItem.Click
' Prompt the user for input
Dim newItem As String = InputBox("Enter the new item:", "Add New
Item")

99
' Check if the user entered a value
If Not String.IsNullOrEmpty(newItem) Then
' Resize the array and add the new item
ReDim Preserve dynamicArray(dynamicArray.Length)
dynamicArray(dynamicArray.Length - 1) = newItem

' Display the updated array in the List Box


UpdateListBox()
End If
End Sub
End Class

100
Output:

A Form in
visual basic
with a
command
button ,list
and labels.

101
An input Box
appears on
Clicking
Command
button.
Allowing to
insert array
element

After, entering new Element


the Array size increase and list
get updated to display each
element.

102
Que-22: WAP in VB to change the background colour of the
form.
Ans:
Algorithm:
Here's an algorithm describing the logic to change the background color of a
form to a random color when a button is clicked.

User Clicks Button Algorithm:

When the user clicks a button (e.g., btnChangeColor):


Inside the button click event handler:
Create a Random object to generate random numbers.
Generate three random values between 0 and 255 for red, green, and blue.
Use the generated values to create a random color.
Set the background color of the form to the random color.
End of Algorithm:

End the algorithm.

103
Code:
Public Class Form1
Private rand As New Random()

Private Sub btnChangeColor_Click(sender As Object, e As EventArgs)


Handles btnChangeColor.Click
' Generate random RGB values
Dim red As Integer = rand.Next(256)
Dim green As Integer = rand.Next(256)
Dim blue As Integer = rand.Next(256)

' Set the background color of the form to a random color


Me.BackColor = Color.FromArgb(red, green, blue)
End Sub
End Class

104
Output:

A form with a command


button Named as click
here to change colour.

On Clicking command button


the form’s colour will change
randomly.
(This time White to black)

105
Que-23: WAP in VB to create a form that contains Label
control, TextBox, Check boxes, radio buttons and command
buttons.
Ans:
Algorithm: The algorithm for the Visual Basic code that creates a form
with various controls. This algorithm describes the steps and logic that the
program follows:

Create a new VB.NET Windows Forms Application:

Open Visual Studio.


Create a new Windows Forms Application project.
Open the Form Designer:

Open the MainForm in the Form Designer.


Set Up Form Properties:

Set the form's title to "VB Form Example."


Set the form's size to 400 pixels in width and 300 pixels in height.
Create and Configure Label Control:

106
Create a new Label control (lblName).
Set the label's text to "Name:".
Set the label's location to (20, 20).
Create and Configure TextBox Control:

Create a new TextBox control (txtName).


Set the text box's location to (100, 20).
Set the text box's size to 200 pixels in width.
Create and Configure CheckBox Control:

Create a new CheckBox control (chkSubscribe).


Set the check box's text to "Subscribe to newsletter."
Set the check box's location to (20, 60).
Create and Configure RadioButton Controls:

Create a new RadioButton control (rbtnMale).

Set the radio button's text to "Male."

Set the radio button's location to (20, 100).

Create another RadioButton control (rbtnFemale).

107
Set the second radio button's text to "Female."

Set the second radio button's location to (120, 100).

Create and Configure Button Control:

Create a new Button control (btnSubmit).


Set the button's text to "Submit."
Set the button's location to (20, 140).
Add Controls to the Form:

Add the label, text box, check box, radio buttons, and button to the form's
Controls collection.
Attach Event Handler:

Attach an event handler (btnSubmit_Click) to the Submit button's click event.


Implement Event Handler:
In the btnSubmit_Click event handler, retrieve the entered name from the
text box.
Display a message box welcoming the user with the entered name.
Run the Application:

108
Compile and run the application to display the form with the specified
controls.
This algorithm outlines the key steps to create a VB.NET Windows Forms
Application with a form containing various controls.

Code:
Public Class MainForm
' Event handler for the form's Load event
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set up the form properties
Me.Text = "VB Form Example"
Me.Size = New Size(400, 300)

' Create and configure a Label control


Dim lblName As New Label()
lblName.Text = "Name:"
lblName.Location = New Point(20, 20)

' Create and configure a TextBox control


Dim txtName As New TextBox()
txtName.Location = New Point(100, 20)
txtName.Size = New Size(200, 20)
109
' Create and configure a CheckBox control
Dim chkSubscribe As New CheckBox()
chkSubscribe.Text = "Subscribe to newsletter"
chkSubscribe.Location = New Point(20, 60)

' Create and configure RadioButton controls


Dim rbtnMale As New RadioButton()
rbtnMale.Text = "Male"
rbtnMale.Location = New Point(20, 100)

Dim rbtnFemale As New RadioButton()


rbtnFemale.Text = "Female"
rbtnFemale.Location = New Point(120, 100)

' Create and configure a CommandButton (Button) control


Dim btnSubmit As New Button()
btnSubmit.Text = "Submit"
btnSubmit.Location = New Point(20, 140)

' Add controls to the form's Controls collection


Me.Controls.Add(lblName)

110
Me.Controls.Add(txtName)
Me.Controls.Add(chkSubscribe)
Me.Controls.Add(rbtnMale)
Me.Controls.Add(rbtnFemale)
Me.Controls.Add(btnSubmit)

' Attach an event handler to the button click event


AddHandler btnSubmit.Click, AddressOf btnSubmit_Click
End Sub

' Event handler for the Submit button click event


Private Sub btnSubmit_Click(sender As Object, e As EventArgs)
' Add your code to handle the button click event
' For example, display a message box with the entered name
Dim enteredName As String = DirectCast(Me.Controls("txtName"),
TextBox).Text
MessageBox.Show("Hello, " & enteredName & "!", "Welcome")
End Sub
End Class

111
Output:

This is a User form with a


label, text box, radio buttons
,checkbox and a command
button.

On Clicking Submit
button , A Message
Box appear with
Welcome Message.

112
Que-24: WAP in VB to create form with List Box .Add items in
the list, delete items in the list,display total number of items
in the list.
Ans:
Algorithm: Algorithm to create form with List Box .Add items in the list,
delete items in the list,display total number of items in the list.

Initialization:

Initialize the form with the necessary controls: ListBox (lstItems), TextBox
(txtNewItem), Buttons (btnAddItem, btnDeleteItem), and a Label
(lblItemCount).
Load Event:

In the form's Load event:


Add three pre-defined items ("Item 1", "Item 2", "Item 3") to the lstItems
ListBox.
Update the label (lblItemCount) to display the total number of items in the
ListBox.
Add Item Button (btnAddItem):

When the "Add Item" button is clicked:

113
Get the text from the txtNewItem TextBox.
Check if the entered text is not empty.
If not empty, add the text as a new item to the lstItems ListBox.
Clear the TextBox.
Update the label to display the updated total number of items.
Delete Item Button (btnDeleteItem):

When the "Delete Item" button is clicked:


Check if an item is selected in the lstItems ListBox (index is not -1).
If an item is selected, remove the selected item from the ListBox.
Update the label to display the updated total number of items.
Update Item Count Method (UpdateItemCount):

This helper method updates the label (lblItemCount) to display the total
number of items in the lstItems ListBox.
Set the text of the label to "Total Items: X" where X is the count of items in
the ListBox (lstItems.Items.Count).
This algorithm outlines the key steps and interactions for adding, deleting,
and counting items in the ListBox.

Code:-
Public Class MainForm
' Event handler for the form's Load event

114
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Add three pre-defined items to the ListBox
lstItems.Items.Add("Item 1")
lstItems.Items.Add("Item 2")
lstItems.Items.Add("Item 3")
UpdateItemCount()
End Sub

' Event handler for the "Add Item" button


Private Sub btnAddItem_Click(sender As Object, e As EventArgs) Handles
btnAddItem.Click
' Get the text from the TextBox
Dim newItem As String = txtNewItem.Text.Trim()

' Add the item to the ListBox if it's not empty


If Not String.IsNullOrEmpty(newItem) Then
lstItems.Items.Add(newItem)
txtNewItem.Clear() ' Clear the TextBox after adding the item
UpdateItemCount()
Else
MessageBox.Show("Enter new element below:", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)

115
End If
End Sub

' Event handler for the "Delete Item" button


Private Sub btnDeleteItem_Click(sender As Object, e As EventArgs) Handles
btnDeleteItem.Click
' Check if an item is selected
If lstItems.SelectedIndex <> -1 Then
' Remove the selected item from the ListBox
lstItems.Items.RemoveAt(lstItems.SelectedIndex)
UpdateItemCount()
Else
MessageBox.Show("Please select an item to delete.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub

' Helper method to update the label displaying the total number of items
Private Sub UpdateItemCount()
lblItemCount.Text = "Total Items: " & lstItems.Items.Count.ToString()
End Sub
End Class

116
Output:

This is a simple
form with a list
having 3 items
and 3 buttons:
Add Item Delete
Item and Print
number of items .

On Clicking Add
Items.
An input dialog
box appears with
a textbox to add
new element.

117
The List
Successfully
updated with
new item.
On clicking
delete item the
selected item
from the list get
removed .

On Clicking
Print Number of
items The label
below get
updated and
print total
number of
items in a list

118
Que-25: WAP to create menu in VB.
Ans:
Algorithm: Here's an algorithm that describes the steps to create a menu
with multiple tabs and elements:

Algorithm: Creating a Menu with Multiple Tabs and Elements

Initialize Form:

Create a new Windows Form application.


Open the form designer.
Add MenuStrip:

Drag and drop a MenuStrip control onto the form.


Create File Menu:

Add a new ToolStripMenuItem to the MenuStrip and set its Text property to
"File."
Add child items for "New," "Open," "Save," and "Exit" under the "File" menu.
Create Edit Menu:

119
Add another ToolStripMenuItem to the MenuStrip and set its Text property to
"Edit."
Add child items for "Cut," "Copy," and "Paste" under the "Edit" menu.
Create Help Menu:

Add a third ToolStripMenuItem to the MenuStrip and set its Text property to
"Help."
Add a child item for "About" under the "Help" menu.
Handle Exit Event:

Implement an event handler for the "Exit" menu item to close the form when
clicked.
Handle About Event:

Implement an event handler for the "About" menu item to display


information about the application.
Set MainMenuStrip:

Set the MainMenuStrip property of the form to the MenuStrip you created.
Test the Form:

Run the application to test the functionality of the menu.


Optional: Customize and Expand:

120
Customize the menus, items, and event handlers based on your application's
requirements.
Add additional tabs, elements, or functionalities as needed.
Compile and Distribute:
Compile the application and distribute it as needed.
This algorithm provides a high-level overview of the steps involved in creating
a menu with multiple tabs and elements in a Visual Basic application.
Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Create MenuStrip
Dim menuStrip As New MenuStrip()

' Create File menu


Dim fileMenu As New ToolStripMenuItem("File")
Dim newItem As New ToolStripMenuItem("New")
Dim openItem As New ToolStripMenuItem("Open")
Dim saveItem As New ToolStripMenuItem("Save")
Dim exitItem As New ToolStripMenuItem("Exit")

' Add items to the File menu

121
fileMenu.DropDownItems.Add(newItem)
fileMenu.DropDownItems.Add(openItem)
fileMenu.DropDownItems.Add(saveItem)
fileMenu.DropDownItems.Add(exitItem)

' Create Edit menu


Dim editMenu As New ToolStripMenuItem("Edit")
Dim cutItem As New ToolStripMenuItem("Cut")
Dim copyItem As New ToolStripMenuItem("Copy")
Dim pasteItem As New ToolStripMenuItem("Paste")

' Add items to the Edit menu


editMenu.DropDownItems.Add(cutItem)
editMenu.DropDownItems.Add(copyItem)
editMenu.DropDownItems.Add(pasteItem)

' Create Help menu


Dim helpMenu As New ToolStripMenuItem("Help")
Dim aboutItem As New ToolStripMenuItem("About")

' Add items to the Help menu


helpMenu.DropDownItems.Add(aboutItem)

122
' Add the menus to the MenuStrip
menuStrip.Items.Add(fileMenu)
menuStrip.Items.Add(editMenu)
menuStrip.Items.Add(helpMenu)

' Set the MenuStrip as the form's MenuStrip


Me.MainMenuStrip = menuStrip
End Sub

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs)


Handles ExitToolStripMenuItem.Click
' Handle the Exit menu item click event
Me.Close()
End Sub

Private Sub AboutToolStripMenuItem_Click(sender As Object, e As


EventArgs) Handles AboutToolStripMenuItem.Click
' Handle the About menu item click event
MessageBox.Show("This is a simple VB.NET menu example.", "About",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class

123
Output :
This is how my menu looks..
There are three tabs: File,Edit,Help. Ans their elements show when hower or
click event happens.

124
Menu Tab with its elements.

Edit tab with its elements

125
Help tab with its elements.

126
Que-26: WAP to create MDI form.
Ans-
Algorithm:- here's a high-level algorithm for creating an MDI (Multiple
Document Interface) application with navigation between two child forms
using command buttons:

Create MDIForm:

Create a new Windows Forms project in your preferred programming


environment.
Design the main MDI form (MDIForm) and set the IsMdiContainer property to
True.
Create Child Forms:

Create two child forms (ChildForm1 and ChildForm2) that you want to display
within the MDI form.
Design the child forms with their respective content and controls.
Add Command Buttons:

Add two command buttons (btnOpenChildForm1 and btnOpenChildForm2) to


the MDI form.
Set the text of the buttons to indicate their respective actions (e.g., "Open
Form 1" and "Open Form 2").

127
Handle Button Click Events:

Implement click event handlers for the command buttons.


In the event handler for btnOpenChildForm1:
Check if ChildForm1 is already open:
If open, activate it.
If not open, create an instance of ChildForm1, set its MdiParent to the MDI
form, and show it.
In the event handler for btnOpenChildForm2:
Check if ChildForm2 is already open:
If open, activate it.
If not open, create an instance of ChildForm2, set its MdiParent to the MDI
form, and show it.
Run the Application:

Run the application and observe the behavior.


Clicking the command buttons should open or activate the corresponding
child forms within the MDI container.
Testing and Refinement:

Test the application to ensure that child forms are opened and navigated
correctly.

128
Refine the design and functionality based on user feedback or specific
requirements.
This algorithm provides a conceptual overview of the steps involved in
creating an MDI application using command buttons.

Code:-
Public Class MDIForm
Private Sub MDIForm_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set the IsMdiContainer property to True.
IsMdiContainer = True
End Sub

Private Sub btnOpenChildForm1_Click(sender As Object, e As EventArgs)


Handles btnOpenChildForm1.Click
' Activate ChildForm1 if it is already open.
For Each childForm As Form In MdiChildren
If TypeOf childForm Is ChildForm1 Then
childForm.Activate()
Exit Sub
End If
Next

129
' If ChildForm1 is not open, create and show it.
Dim childForm1 As New ChildForm1()
childForm1.MdiParent = Me
childForm1.Show()
End Sub

Private Sub btnOpenChildForm2_Click(sender As Object, e As EventArgs)


Handles btnOpenChildForm2.Click
' Activate ChildForm2 if it is already open.
For Each childForm As Form In MdiChildren
If TypeOf childForm Is ChildForm2 Then
childForm.Activate()
Exit Sub
End If
Next

' If ChildForm2 is not open, create and show it.


Dim childForm2 As New ChildForm2()
childForm2.MdiParent = Me
childForm2.Show()
End Sub
End Class

130
Output:

Here There are


This is an
two command
example button named
of MDI Child form1 and
form. Child form 2
Click on button
to load a
respective form.

131
Child Form 1 Child Form 2

132
Que-27: WAP to create and use picture box in VB.
Ans:
Algorithm: Here is an algorithm, without specific code, for creating and using
a PictureBox in a VB application:

Create a new VB Windows Forms Application:


Start by creating a new Windows Forms Application using your preferred VB
development environment.

Design the Form:


Open the Form Designer and design your form layout. Drag and drop a
PictureBox control from the Toolbox onto the form.
Set PictureBox Properties:
Configure the properties of the PictureBox such as its location, size, and any
other visual settings based on your layout preferences.
Declare a PictureBox Variable:
In the code-behind of your form, declare a PictureBox variable at the class
level. This variable will represent the PictureBox control on your form.
Load Image into PictureBox:
In the appropriate initialization event (e.g., Form_Load), load an image into
the PictureBox. Specify the file path to the image you want to display.

Adjust Image Size Mode (Optional):

133
Depending on your requirements, you may want to set the PictureBox's
SizeMode property to control how the image is displayed within the
PictureBox (e.g., Stretch, Center, etc.).

Run the Application:


Build and run your application. The PictureBox should now display the
specified image on the form according to the configured properties.

This algorithm provides a high-level overview of the steps involved in creating


and using a PictureBox in a VB application.
Code:
Public Class Form1
' Declare a PictureBox variable
Dim pictureBox1 As New PictureBox()

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
' Set properties for the PictureBox
pictureBox1.Location = New Point(50, 50)
pictureBox1.Size = New Size(200, 150)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage ' Adjust the
image size mode as needed

' Load an image into the PictureBox


134
pictureBox1.Image = Image.FromFile("C:\Path\To\Your\Image.jpg") '
Provide the correct path to your image file

' Add the PictureBox to the form's Controls collection


Me.Controls.Add(pictureBox1)
End Sub
End Class

135
Output:

136
Que-28: WAP to create horizontal scrollbar and a textbox in
VB. The font size of text box should increase and decrease
according to the scrollbar.

Sol:
Algorithm: an algorithmic representation of how you can create a horizontal
scrollbar and a textbox in VB, where the font size of the textbox increases or
decreases according to the scrollbar's position:
Initialize Form:
Create a new Windows Forms Application.
Design the form with a HorizontalScrollBar (HScrollBar) and a TextBox
(TextBox).
Set Initial Values:
Set the properties of the scrollbar:
Minimum value for the minimum font size.
Maximum value for the maximum font size.
LargeChange for the increment/decrement size.
Set the initial font size of the textbox to a default value.
Handle Scroll Event:

Attach an event handler to the scrollbar's Scroll event.


In the event handler:
137
Adjust the font size of the textbox based on the scrollbar's position.
The provided code in the previous response demonstrates the
implementation of the above algorithm in VB.
Code:
Public Class Form1
Private Sub HScrollBar1_Scroll(sender As Object, e As ScrollEventArgs)
Handles HScrollBar1.Scroll
' Adjust the font size of the textbox based on the scrollbar's position
TextBox1.Font = New Font(TextBox1.Font.FontFamily, HScrollBar1.Value)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set the initial values for the scrollbar and textbox
HScrollBar1.Minimum = 8 ' Minimum font size
HScrollBar1.Maximum = 24 ' Maximum font size
HScrollBar1.LargeChange = 1 ' Increment/decrement size

' Set the initial font size of the textbox


TextBox1.Font = New Font(TextBox1.Font.FontFamily, HScrollBar1.Value)
End Sub
End Class

138
Output:

Font size Ranges


Between 8-24.

Font size =14

Font Size:24 (Max)

139
Que-29: WAP in VB to create three vertical scrollbars(For RGB).
The background colour of the form should change according to
the three scrollbars.
Ans:
Algorithm: Here's a step-by-step algorithm for the task you described, without
specific code:

Initialize Form:

Create a new VB project and add a Form to it.


Add Scrollbars:

Add three vertical scrollbars to the Form, naming them HScrollBarRed,


HScrollBarGreen, and HScrollBarBlue.
Initialize Scrollbar Values:

Set the initial values of the three scrollbars to 0.


Form Load Event:

Implement the Form's Load event.


Set the initial values of the scrollbars to 0.
Call a function (UpdateFormColor) to update the form's background color based
on the scrollbar values.
Scrollbar Event Handlers:
140
Implement event handlers for each scrollbar (e.g., HScrollBarRed_Scroll,
HScrollBarGreen_Scroll, and HScrollBarBlue_Scroll).
In each event handler, call the UpdateFormColor function.
UpdateFormColor Function:

Implement a function (UpdateFormColor) that does the following:


Retrieve the current values of the Red, Green, and Blue scrollbars.
Set the form's background color using Color.FromArgb with the retrieved values.
Update the form's title to display the current RGB values.
Testing:

Run the program and observe the changes in the form's background color as you
adjust the scrollbars.
This algorithm outlines the logical steps to achieve the desired functionality.

Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set initial values for scrollbars
HScrollBarRed.Value = 0
HScrollBarGreen.Value = 0
HScrollBarBlue.Value = 0

141
' Update form's background color
UpdateFormColor()
End Sub

' Event handler for the Red ScrollBar


Private Sub HScrollBarRed_Scroll(sender As Object, e As ScrollEventArgs)
Handles HScrollBarRed.Scroll
UpdateFormColor()
End Sub

' Event handler for the Green ScrollBar


Private Sub HScrollBarGreen_Scroll(sender As Object, e As ScrollEventArgs)
Handles HScrollBarGreen.Scroll
UpdateFormColor()
End Sub

' Event handler for the Blue ScrollBar


Private Sub HScrollBarBlue_Scroll(sender As Object, e As ScrollEventArgs)
Handles HScrollBarBlue.Scroll
UpdateFormColor()
End Sub

' Function to update the form's background color based on scroll bar values

142
Private Sub UpdateFormColor()
Dim redValue As Integer = HScrollBarRed.Value
Dim greenValue As Integer = HScrollBarGreen.Value
Dim blueValue As Integer = HScrollBarBlue.Value

' Set the form's background color based on scroll bar values
Me.BackColor = Color.FromArgb(redValue, greenValue, blueValue)

' Display current RGB values in the form's title


Me.Text = $"RGB({redValue}, {greenValue}, {blueValue})"
End Sub
End Class

143
Output:

A form with 3 horizontal bars used to change back ground colour of the form.
RGB stands For ( red,green,blue)

RGB values show here!

144
Que-30: WAP in VB to show and hide form.
Ans:
Algorithm: An algorithmic description of the behavior you want to achieve:

Main Form (Form1):

Display Form1 with two buttons: btnShowForm2 and btnShowForm3.

When btnShowForm2 is clicked:

Hide Form1.
Show Form2.
When btnShowForm3 is clicked:

Hide Form1.
Show Form3.
Form2 and Form3:

Display Form2 or Form3, each with a button btnGoBack.


When btnGoBack is clicked:
Hide the current form (Form2 or Form3).
Show Form1.
145
This algorithm outlines the steps for showing and hiding forms in response to
button clicks.

Code For Form1:


Public Class Form1
Private Sub btnShowForm2_Click(sender As Object, e As EventArgs) Handles
btnShowForm2.Click
Form2.Show()
Me.Hide()
End Sub

Private Sub btnShowForm3_Click(sender As Object, e As EventArgs) Handles


btnShowForm3.Click
Form3.Show()
Me.Hide()
End Sub
End Class

Code for form 2:


Public Class Form2
Private Sub btnGoBack_Click(sender As Object, e As EventArgs) Handles
btnGoBack.Click
Form1.Show()

146
Me.Hide()
End Sub
End Class

Code for form 3 :


Public Class Form3
Private Sub btnGoBack_Click(sender As Object, e As EventArgs) Handles
btnGoBack.Click
Form1.Show()
Me.Hide()
End Sub
End Class

147
Output:

This is a user form with two buttons

Show Show
Form 2 Form 3
(this (this
button button
hide hide
current current
form 1 form 1
and load
and load
form 3)
form 2)

Form 2 with a button Show form1 Form 3 with a button Show form1
( this will hide current form 2 and ( this will hide current form 3 and
Show form 1) Show form 1)

148
149

You might also like