0% found this document useful (0 votes)
5 views

Program in Details

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Program in Details

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

1. Write a console application program in VB.Net to find the area of a rectangle.

Here's a VB.Net console application program to find the area of a rectangle:

VB.Net
Module RectangleAreaCalculator

Sub Main()
Dim length As Double
Dim width As Double
Dim area As Double

Console.WriteLine("Enter the length of the rectangle: ")


length = Double.Parse(Console.ReadLine())

Console.WriteLine("Enter the width of the rectangle: ")


width = Double.Parse(Console.ReadLine())

area = length * width

Console.WriteLine("Area of the rectangle: {0:F2}", area)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program is similar to the circle calculator but focuses on rectangles.

 Variables: It declares variables length, width, and area for rectangle dimensions
and the calculated area.
 User Input: It prompts the user for both length and width using Console.WriteLine
and reads the inputs with Console.ReadLine, converting them to Doubles.
 Calculation: It calculates the area using the formula length * width.
 Output: It displays the calculated area with a formatted string ({0:F2}) for two
decimal places.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program demonstrates how to calculate the area of a rectangle using VB.Net console
application features.

2. Write a console application program in VB.Net to find area of circle and


Circumference of circle.
Here's a VB.Net console application program to find the area and circumference of a circle:

VB.Net
Module CircleCalculator

' Constant value for Pi


Const Pi As Double = Math.PI ' Uses Math.PI for a more accurate value

Sub Main()
' Declare variables
Dim radius As Double
Dim area As Double
Dim circumference As Double

' Prompt user for radius


Console.WriteLine("Enter the radius of the circle: ")
radius = Double.Parse(Console.ReadLine())

' Calculate area


area = Pi * radius * radius

' Calculate circumference


circumference = 2 * Pi * radius

' Display results


Console.WriteLine("Area of the circle: {0:F2}", area)
Console.WriteLine("Circumference of the circle: {0:F2}", circumference)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program defines a Module named CircleCalculator with a Main sub that executes
when the program runs.

 Constants: It defines a constant Pi using Math.PI for a more accurate value.


 Variables: It declares variables radius, area, and circumference to store user input
and calculated values.
 User Input: It prompts the user for the radius using Console.WriteLine and reads
the input using Console.ReadLine. It then converts the input to a Double using
Double.Parse.
 Calculations: It calculates the area using the formula Pi * radius * radius and
circumference using 2 * Pi * radius.
 Output: It displays the calculated area and circumference using formatted strings
({0:F2}) for two decimal places.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This is a simple example demonstrating console input and output with calculations for circle
area and circumference. You can modify it further to add features like error handling or loop
for multiple calculations.
3. Write a console application program in VB.Net to print day of week.

Here's a VB.Net console application program to print the day of the week:

VB.Net
Module DayOfWeekPrinter

Sub Main()
Dim currentDate As DateTime = DateTime.Now

Dim dayOfWeek As DayOfWeek = currentDate.DayOfWeek

Dim dayName As String = dayOfWeek.ToString("dddd") ' "dddd" format


for full day name

Console.WriteLine("Today is: {0}", dayName)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program utilizes the DateTime structure and its properties:

 Get Current Date: It retrieves the current date and time using DateTime.Now.
 Day of Week: It extracts the day of the week from the DateTime object using the
DayOfWeek property.
 Convert to String: It converts the DayOfWeek enum value to a string representation
using the ToString method. The format string "dddd" specifies the full day name
(e.g., "Monday").
 Print Output: It displays the day of the week using Console.WriteLine.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program demonstrates how to access the current date and extract the day of the week for
printing in VB.Net.
4. Write a console application program in VB.Net to make calculator.

Here's a VB.Net console application program for a basic calculator with addition, subtraction,
multiplication, and division functionalities:

VB.Net
Module BasicCalculator

Sub Main()
' Declare variables
Dim num1 As Double
Dim num2 As Double
Dim operation As String

' Loop for multiple calculations


Do While True
' Get first number from user
Console.WriteLine("Enter the first number: ")
num1 = Double.Parse(Console.ReadLine())

' Get operator from user


Console.WriteLine("Enter the operator (+, -, *, /): ")
operation = Console.ReadLine()

' Validate operator input


If Not ValidateOperator(operation) Then
Console.WriteLine("Invalid operator. Please try again.")
Continue For ' Skip to the next iteration of the loop
End If

' Get second number from user


Console.WriteLine("Enter the second number: ")
num2 = Double.Parse(Console.ReadLine())

' Perform calculation based on operator


Dim result As Double = PerformCalculation(num1, num2, operation)

' Display result


Console.WriteLine("Result: {0:F2}", result)

' Ask if user wants another calculation


Console.WriteLine("Do you want to perform another calculation? (y/n):
")
Dim answer As String = Console.ReadLine().ToLower()

' Exit loop if user enters 'n'


If answer <> "y" Then Exit Do
Loop

Console.WriteLine("Calculator closed.")
Console.ReadKey()
End Sub

' Function to validate user entered operator


Function ValidateOperator(op As String) As Boolean
Return op = "+" Or op = "-" Or op = "*" Or op = "/"
End Function

' Function to perform calculation based on operator


Function PerformCalculation(num1 As Double, num2 As Double, op As String)
As Double
Select Case op
Case "+"
Return num1 + num2
Case "-"
Return num1 - num2
Case "*"
Return num1 * num2
Case "/"
' Handle division by zero
If num2 = 0 Then
Console.WriteLine("Error: Cannot divide by zero.")
Return Double.NaN ' Not a Number
Else
Return num1 / num2
End If
Default
Return Double.NaN ' Invalid operator case
End Select
End Function

End Module
Use code with caution.

This program incorporates features for a more robust calculator:

 Loop: It uses a Do While loop to allow for multiple calculations until the user
chooses to exit.
 Error Handling: It validates the user-entered operator using the ValidateOperator
function and handles division by zero within the PerformCalculation function.
 Modularity: It separates the calculation logic into a PerformCalculation function
for better organization.
 User Interaction: It guides the user through the process with clear prompts and
allows them to continue calculating or exit.
 Output: It displays the calculated result with a formatted string ({0:F2}) for two
decimal places.

This is a basic example, and you can further enhance it by adding features like exponential
calculations, memory functions, or more robust error handling.

5. Write a console application program in VB.Net to take two numbers from user and
check whether they are equal or not.

Here's a VB.Net console application program to take two numbers from the user and check if
they are equal:

VB.Net
Module NumberEqualityChecker

Sub Main()
Dim num1 As Double
Dim num2 As Double
Console.WriteLine("Enter the first number: ")
num1 = Double.Parse(Console.ReadLine())

Console.WriteLine("Enter the second number: ")


num2 = Double.Parse(Console.ReadLine())

Dim areEqual As Boolean = Math.Abs(num1 - num2) < 0.00001 ' Adjust


tolerance as needed

If areEqual Then
Console.WriteLine("The numbers are equal.")
Else
Console.WriteLine("The numbers are not equal.")
End If

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program addresses the potential issue of floating-point precision:

 Tolerance: It checks for equality using Math.Abs(num1 - num2) < 0.00001 to


account for small differences due to floating-point representation. Adjust the tolerance
value (e.g., 0.001) based on your desired level of precision.
 Clarity: It uses clear variable names and comments to enhance readability.

This program demonstrates how to compare two user-entered numbers for equality while
considering floating-point precision in VB.Net.

6. Write a console application program in VB.Net to count the total even number
present from range 1 to 50.

Here's a VB.Net console application program to count the total even numbers present from
range 1 to 50:

VB.Net
Module EvenNumberCounter

Sub Main()
' Initialize a counter for even numbers
Dim evenCount As Integer = 0

' Loop through the range from 1 to 50 (inclusive)


For num As Integer = 1 To 50
' Check if the number is even using modulo operator
If num Mod 2 = 0 Then
evenCount += 1
End If
Next

' Print the total count of even numbers


Console.WriteLine("Total even numbers between 1 and 50: {0}",
evenCount)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program utilizes a loop and the modulo operator (Mod) for efficient even number
counting:

 Counter: It declares an evenCount variable to store the total count.


 Loop: It uses a For loop to iterate through the numbers from 1 to 50.
 Modulo Check: Inside the loop, it checks if the current number (num) leaves no
remainder when divided by 2 using num Mod 2 = 0. If true, it's even.
 Increment Counter: If the number is even, it increments the evenCount.
 Print Result: After the loop, it displays the total count of even numbers using
Console.WriteLine.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This is a concise and efficient solution for counting even numbers in a given range.

7. Write a console application program in VB.Net to print following pattern-1 8 27 64


125 216 343 512 729 1000.

Here's a VB.Net console application program to print the pattern 1, 8, 27, 64, 125, 216, 343,
512, 729, 1000:

VB.Net
Module PatternPrinter

Sub Main()
' Loop through numbers from 1 to 10
For num As Integer = 1 To 10
' Calculate the cube of the number
Dim cube As Double = Math.Pow(num, 3)

' Print the cube


Console.WriteLine(cube)
Next

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.
This program utilizes the Math.Pow function and a loop to generate the pattern:

 Loop: It uses a For loop to iterate through numbers from 1 to 10.


 Cube Calculation: Inside the loop, it calculates the cube of the current number (num)
using Math.Pow(num, 3).
 Print Output: It displays the calculated cube value using Console.WriteLine.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program demonstrates how to generate a pattern based on the cube of a sequence of
numbers.

8. Write a console application program in VB.Net to print even and odd number up to 100.

Here's a VB.Net console application program to print even and odd numbers up to 100:

VB.Net
Module EvenOddPrinter

Sub Main()
' Loop through numbers from 1 to 100
For num As Integer = 1 To 100

' Check if the number is even using modulo operator


If num Mod 2 = 0 Then
Console.WriteLine("Even: {0}", num)
Else
Console.WriteLine("Odd: {0}", num)
End If
Next

Console.WriteLine("Finished printing even and odd numbers.")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program combines the concepts of even number checking and console output:

 Loop: It uses a For loop to iterate through numbers from 1 to 100.


 Modulo Check: Inside the loop, it checks if the current number (num) is even using
num Mod 2 = 0.
 Conditional Printing: Based on the modulo check, it prints the number either as
"Even" or "Odd" using Console.WriteLine with formatted strings ({0}) for the
number.
 Completion Message: After the loop finishes, it displays a message indicating
completion.
 User Interaction: It uses Console.ReadKey to wait for user input before closing the
program.

This program provides a clear separation of even and odd numbers during printing. You can
modify it to print them on separate lines or in a different format.
9. Write a console application program in VB.Net to print Fibonacci series.

Here's a VB.Net console application program to print the Fibonacci series up to a user-
specified number:

VB.Net
Module FibonacciPrinter

Sub Main()
' Get the number of terms from the user
Dim numTerms As Integer
Console.WriteLine("Enter the number of terms for the Fibonacci series:
")
numTerms = Integer.Parse(Console.ReadLine())

' Handle invalid input (non-positive number)


If numTerms <= 0 Then
Console.WriteLine("Invalid input. Please enter a positive number.")
Exit Sub ' Exit the program if input is not valid
End If

' Initialize first two Fibonacci numbers


Dim prevNum As Integer = 0
Dim currNum As Integer = 1

' Print the first two terms (special cases)


Console.WriteLine(prevNum)
Console.WriteLine(currNum)

' Loop to generate and print Fibonacci numbers


For i As Integer = 2 To numTerms - 1
Dim nextNum As Integer = prevNum + currNum
Console.WriteLine(nextNum)
prevNum = currNum
currNum = nextNum
Next

Console.WriteLine("Fibonacci series printed successfully.")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program incorporates user input, error handling, and efficient loop-based calculation for
the Fibonacci series:

 User Input: It prompts the user to enter the desired number of terms using
Console.WriteLine and reads the input using Console.ReadLine. It converts the
input to an integer using Integer.Parse.
 Error Handling: It checks if the user entered a non-positive number and displays an
error message if so, exiting the program using Exit Sub.
 Initialization: It initializes the first two Fibonacci numbers (prevNum and currNum)
with 0 and 1, respectively.
 Special Case Handling: It prints the first two terms (0 and 1) outside the loop as they
are special cases.
 Loop for Fibonacci Calculation: It uses a For loop that iterates from 2 to numTerms
- 1 (excluding the first two terms).
o Inside the loop, it calculates the next Fibonacci number by adding the previous
two (nextNum = prevNum + currNum).
o It then prints the calculated nextNum.
o It updates the prevNum and currNum values for the next iteration.
 Success Message: After the loop, it displays a message indicating successful printing.
 User Interaction: It uses Console.ReadKey to wait for user input before closing the
program.

This program demonstrates a well-structured approach to generate and print the Fibonacci
series in VB.Net.

10. Write a console application program in VB.Net to find greatest of three numbers.

Here's a VB.Net console application program to find the greatest of three numbers:

VB.Net
Module GreatestNumberFinder

Sub Main()
' Declare variables
Dim num1 As Double
Dim num2 As Double
Dim num3 As Double
Dim greatest As Double

' Get first number from user


Console.WriteLine("Enter the first number: ")
num1 = Double.Parse(Console.ReadLine())

' Get second number from user


Console.WriteLine("Enter the second number: ")
num2 = Double.Parse(Console.ReadLine())

' Get third number from user


Console.WriteLine("Enter the third number: ")
num3 = Double.Parse(Console.ReadLine())

' Find the greatest number using nested if statements


greatest = num1
If num2 > greatest Then
greatest = num2
End If
If num3 > greatest Then
greatest = num3
End If

' Display the greatest number


Console.WriteLine("The greatest number is: {0:F2}", greatest)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program utilizes nested If statements for a clear approach to finding the greatest
number:

 Variables: It declares variables for the three numbers (num1, num2, num3) and a
variable to store the greatest number (greatest).
 User Input: It prompts the user to enter the three numbers using Console.WriteLine
and reads the inputs using Console.ReadLine, converting them to Doubles.
 Nested If Statements: It initializes greatest with num1. It then checks if num2 and
num3 are greater than the current greatest value using nested If statements. If a
number is greater, it becomes the new greatest.
 Display Result: After the comparisons, it displays the greatest number with a
formatted string ({0:F2}) for two decimal places.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program demonstrates a simple and readable approach to finding the greatest of three
user-entered numbers. You can modify it to use a more concise approach with conditional
operators if desired.

11. Write a console application program in VB.Net to take marks in five subjects and
calculate total and percentage.

Here's a console application program in VB.Net to take marks in five subjects and calculate
total and percentage:

VB.Net
Module MarksCalculator

Sub Main()
' Declare variables
Dim subject1 As Double
Dim subject2 As Double
Dim subject3 As Double
Dim subject4 As Double
Dim subject5 As Double
Dim totalMarks As Double
Dim percentage As Double

' Get marks for each subject from user


Console.WriteLine("Enter marks for subject 1: ")
subject1 = Double.Parse(Console.ReadLine())
Console.WriteLine("Enter marks for subject 2: ")
subject2 = Double.Parse(Console.ReadLine())
Console.WriteLine("Enter marks for subject 3: ")
subject3 = Double.Parse(Console.ReadLine())
Console.WriteLine("Enter marks for subject 4: ")
subject4 = Double.Parse(Console.ReadLine())
Console.WriteLine("Enter marks for subject 5: ")
subject5 = Double.Parse(Console.ReadLine())

' Calculate total marks


totalMarks = subject1 + subject2 + subject3 + subject4 + subject5

' Calculate percentage


percentage = totalMarks / 500 * 100 ' Assuming maximum marks per
subject is 100

' Display results


Console.WriteLine("Total Marks: {0:F2}", totalMarks)
Console.WriteLine("Percentage: {0:F2}%", percentage)

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program addresses clarity and potential issues:

 Variable Naming: It uses descriptive variable names for subjects and marks.
 User Input: It prompts the user to enter marks for each subject individually using
Console.WriteLine and reads the inputs with Console.ReadLine, converting them
to Doubles.
 Calculation: It calculates the total marks by summing up the marks from each
subject.
 Percentage Calculation: It calculates the percentage by dividing the total marks by
the assumed maximum possible marks (500, assuming 100 marks per subject) and
multiplying by 100. You can adjust the maximum marks based on your requirement.
 Output: It displays the calculated total marks and percentage with formatted strings
({0:F2}) for two decimal places.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program provides a clear and functional solution for calculating total marks and
percentage from five user-entered subject marks in VB.Net.

12. Write a console application program in VB.Net to print following series- 1 4 9 16 25


36 49 64 81 100.

Here's a VB.Net console application program to print the series 1, 4, 9, 16, 25, 36, 49, 64, 81,
100:

VB.Net
Module SquareSeriesPrinter

Sub Main()
' Loop through numbers from 1 to 10
For num As Integer = 1 To 10
' Square the number
Dim square As Double = num * num

' Print the square


Console.WriteLine(square)
Next

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program utilizes a loop to generate the series of squares:

 Loop: It uses a For loop to iterate through numbers from 1 to 10.


 Square Calculation: Inside the loop, it squares the current number (num) using num *
num and stores the result in square.
 Print Output: It displays the calculated square value using Console.WriteLine.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This is a concise and efficient solution for printing the series of squares from 1 to 10.

13. Write a console application program in VB.Net to generate table of given number.

Here's a VB.Net console application program to generate the multiplication table of a given
number:

VB.Net
Module MultiplicationTableGenerator

Sub Main()
' Get the number from the user
Dim num As Integer
Console.WriteLine("Enter a number: ")
num = Integer.Parse(Console.ReadLine())

' Print header for the table


Console.WriteLine("Multiplication Table of {0}", num)
Console.WriteLine("---------------------")

' Loop through numbers from 1 to 10 for multiplication


For i As Integer = 1 To 10
' Calculate the product
Dim product As Integer = num * i

' Display the multiplication in a formatted table-like manner


Console.WriteLine("{0} x {1} = {2}", num, i, product)
Next

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program incorporates user input and formatted output for a well-presented table:

 User Input: It prompts the user to enter a number using Console.WriteLine and
reads the input with Console.ReadLine, converting it to an Integer.
 Header: It displays a header for the multiplication table using Console.WriteLine
with the entered number.
 Loop for Multiplication: It uses a For loop to iterate through numbers from 1 to 10.
 Calculation and Output: Inside the loop, it calculates the product (num * i). It then
displays the multiplication in a formatted string ({0} x {1} = {2}) with
placeholders for the number, multiplier, and product, creating a table-like layout.
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program demonstrates how to generate and display a multiplication table for a user-
specified number in VB.Net.

14. Write a console application program in VB.Net to check whether entered input is
alphabet, digit or special symbol.

Here's a VB.Net console application program to check whether the entered input is an
alphabet, digit, or special symbol:

VB.Net
Module InputChecker

Sub Main()
' Get input from user
Dim input As Char = Console.ReadKey().KeyChar

' Check for alphabet (uppercase or lowercase)


If Char.IsLetter(input) Then
Console.WriteLine("The input '{0}' is an alphabet.", input)
ElseIf Char.IsDigit(input) Then ' Check for digit
Console.WriteLine("The input '{0}' is a digit.", input)
Else ' If not alphabet or digit, it's a special symbol
Console.WriteLine("The input '{0}' is a special symbol.", input)
End If

Console.WriteLine("Press any key to close...")


Console.ReadKey()
End Sub

End Module
Use code with caution.

This program utilizes the Char class and its methods for efficient input checking:
 User Input: It reads a single character input from the user using
Console.ReadKey().KeyChar.
 Alphabet Check: It uses Char.IsLetter(input) to check if the input is an alphabet
(either uppercase or lowercase).
 Digit Check: If not an alphabet, it checks for a digit using Char.IsDigit(input).
 Special Symbol: If neither alphabet nor digit, it's considered a special symbol.
 Output: Based on the checks, it displays a message indicating whether the input is an
alphabet, digit, or special symbol using formatted strings ('{0}').
 User Interaction: It prompts the user to press any key to close the program using
Console.ReadKey.

This program leverages built-in methods for character classification, making it concise and
efficient.

15. Design a Calculator using VB.Net.

Here's a VB.Net Windows Forms application design for a basic calculator with functionalities
like addition, subtraction, multiplication, division, and clear operations:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. In the toolbox, find and drag the following controls onto the form:
o Two TextBox controls for user input (numbers).
o Several Button controls for numbers (0-9), operators (+, -, *, /), and special
functions (".", "C").
o A Label control to display the current operation (optional).
o A Label control to display the result (optional).

Code Implementation:

1. Double-click on each button to create event handlers for the Click event.
2. In the code for each number button's Click event handler, append the clicked number
to the appropriate TextBox control (e.g., txtNumber1.Text += button1.Text).
3. In the code for the operator buttons' Click event handler, store the operator in a
variable (e.g., operator = "+"). You can optionally display the operator on the label
control.
4. In the code for the "." button's Click event handler, check if a decimal point already
exists in the TextBox and add one if not (e.g., If Not
txtNumber1.Text.Contains(".") Then txtNumber1.Text += ".").
5. In the code for the "C" button's Click event handler, clear both TextBoxes and any
displayed operator/result (e.g., txtNumber1.Text = "", txtNumber2.Text = "",
operator = "").
6. Create a separate function (or button click event handler) for the "Equals"
functionality:
o Parse the values from both TextBoxes to Doubles (e.g., num1 =
Double.Parse(txtNumber1.Text), num2 =
Double.Parse(txtNumber2.Text)).
o Use an If statement to check the stored operator and perform the
corresponding calculation (e.g., If operator = "+" Then result = num1
+ num2).
o Handle division by zero error using a Try...Catch block (optional).
o Display the result in the designated Label control (e.g., lblResult.Text =
result.ToString()).

Additional Considerations:

 You can enhance the user experience by adding features like:


o Memory functions (store and recall previous results).
o Error handling for invalid inputs (e.g., non-numeric characters).
o More advanced operations (e.g., square root, exponentiation).
 Use descriptive variable names and comments to improve code readability.

Example Code Snippet (Button Click Event Handler for "Equals")

VB.Net
Private Sub btnEquals_Click(sender As Object, e As EventArgs) Handles
btnEquals.Click
Try
Dim num1 As Double = Double.Parse(txtNumber1.Text)
Dim num2 As Double = Double.Parse(txtNumber2.Text)
Dim result As Double

Select Case operator


Case "+"
result = num1 + num2
Case "-"
result = num1 - num2
Case "*"
result = num1 * num2
Case "/"
If num2 = 0 Then
Throw New DivideByZeroException("Error: Cannot divide by zero.")
Else
result = num1 / num2
End If
Default
' Handle invalid operator (optional)
End Select

lblResult.Text = result.ToString()
Catch ex As DivideByZeroException
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
Use code with caution.

This design provides a basic structure for a calculator application in VB.Net. You can
customize and extend it based on your desired features and complexity.

16. Design a login form using VB.Net.


Here's a VB.Net Windows Forms application design for a simple login form:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. In the toolbox, find and drag the following controls onto the form:
o Two TextBox controls: one for username and one for password.
o A Label control for each TextBox to display labels like "Username" and
"Password".
o A Button control for login.
o (Optional) A CheckBox control for "Remember Me" functionality.

Code Implementation:

1. Double-click on the login button to create an event handler for the Click event.
2. In the code for the login button's Click event handler:
o Get the username and password from the corresponding TextBox controls
(e.g., username = txtUsername.Text, password = txtPassword.Text).
o Implement user authentication logic (replace with your actual authentication
method):
 This could involve comparing the entered credentials with data stored
in a database, text file, or hardcoded values (for demonstration
purposes).
o If the credentials are valid:
 You can either:
 Close the login form and open a new form for the main
application.
 Display a success message on the login form itself.
o If the credentials are invalid:
 Display an error message to the user.
3. (Optional) If you have a "Remember Me" checkbox:
o In the checkbox's CheckedChanged event handler, store the username in a
persistent location (e.g., application settings) if checked, and retrieve it on
form load to pre-populate the username TextBox.

Example Code Snippet (Login Button Click Event Handler):

VB.Net
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles
btnLogin.Click
Dim username As String = txtUsername.Text
Dim password As String = txtPassword.Text

' Replace this with your actual authentication logic


If username = "admin" And password = "password123" Then
' Login successful (replace with your desired action)
MessageBox.Show("Login successful!", "Success", MessageBoxButtons.OK,
MessageBoxIcon.Information)
' Close this form and open the main application form (example)
Me.Close()
' Or display a success message on this form
Else
MessageBox.Show("Invalid username or password.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Use code with caution.

Additional Considerations:

 Use secure password hashing techniques for storing passwords if you're connecting to
a database.
 Implement input validation to ensure the user enters a username and password before
attempting login.
 Enhance the user interface with features like:
o Password masking using the PasswordChar property of the password
TextBox.
o A "Forgot Password" functionality.

This design provides a starting point for creating a login form in VB.Net. Remember to adapt
the authentication logic based on your specific requirements and data storage methods.

17. Design a form having ListBox and show the functionality of ListBox.

Here's a VB.Net Windows Forms application design showcasing ListBox functionalities:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. In the toolbox, find and drag the following controls onto the form:
o A ListBox control.
o Two buttons: one for adding items and another for removing items.
o (Optional) A TextBox control for entering new items to add.
o Two labels: one for the ListBox and another (optional) for the TextBox.

Code Implementation:

1. Double-click on the "Add" button to create an event handler for the Click event.
2. In the code for the "Add" button's Click event handler:
o If an optional TextBox is used (for user input): Get the item text from the
TextBox (e.g., newItem = txtNewItem.Text).
o Otherwise, add a predefined item directly (e.g., newItem = "New Item").
o Add the item to the ListBox using the Items.Add method (e.g.,
lstItems.Items.Add(newItem)).
o Optionally, clear the TextBox after adding the item.
3. Double-click on the "Remove" button to create an event handler for the Click event.
4. In the code for the "Remove" button's Click event handler:
o Check if an item is selected in the ListBox using the SelectedIndex property
(e.g., If lstItems.SelectedIndex >= 0 Then).
o If an item is selected, remove it using the Items.RemoveAt method (e.g.,
lstItems.Items.RemoveAt(lstItems.SelectedIndex)).
o Optionally, display a message if no item is selected for removal.
5. (Optional) Set the SelectionMode property of the ListBox to MultiSimple if you
want to allow users to select multiple items for removal.

Example Code Snippet (Add and Remove Button Click Events):

VB.Net
' Add Button Click Event Handler
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
Dim newItem As String
If Not String.IsNullOrEmpty(txtNewItem.Text) Then ' Check if TextBox has
text
newItem = txtNewItem.Text
lstItems.Items.Add(newItem)
txtNewItem.Text = "" ' Clear the TextBox after adding
Else
MessageBox.Show("Please enter an item to add.", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

' Remove Button Click Event Handler


Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles
btnRemove.Click
If lstItems.SelectedIndex >= 0 Then
lstItems.Items.RemoveAt(lstItems.SelectedIndex)
Else
MessageBox.Show("Please select an item to remove.", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Use code with caution.

Additional Considerations:

 You can pre-populate the ListBox with items during form load using a loop to add
them programmatically.
 The ListBox allows you to access and manipulate selected items using its
SelectedIndex and SelectedItem properties.
 You can customize the appearance of the ListBox by setting properties like
ForeColor, BackColor, and Font.

This design demonstrates basic functionalities of a ListBox control in VB.Net. You can
extend it further based on your specific needs.

18. Design a form having ComboBox with various items and show the selected item in a
ListBox.

Here's a VB.Net Windows Forms application design showcasing ListBox functionalities:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. In the toolbox, find and drag the following controls onto the form:
o A ListBox control.
o Two buttons: one for adding items and another for removing items.
o (Optional) A TextBox control for entering new items to add.
o Two labels: one for the ListBox and another (optional) for the TextBox.

Code Implementation:

1. Double-click on the "Add" button to create an event handler for the Click event.
2. In the code for the "Add" button's Click event handler:
o If an optional TextBox is used (for user input): Get the item text from the
TextBox (e.g., newItem = txtNewItem.Text).
o Otherwise, add a predefined item directly (e.g., newItem = "New Item").
o Add the item to the ListBox using the Items.Add method (e.g.,
lstItems.Items.Add(newItem)).
o Optionally, clear the TextBox after adding the item.
3. Double-click on the "Remove" button to create an event handler for the Click event.
4. In the code for the "Remove" button's Click event handler:
o Check if an item is selected in the ListBox using the SelectedIndex property
(e.g., If lstItems.SelectedIndex >= 0 Then).
o If an item is selected, remove it using the Items.RemoveAt method (e.g.,
lstItems.Items.RemoveAt(lstItems.SelectedIndex)).
o Optionally, display a message if no item is selected for removal.
5. (Optional) Set the SelectionMode property of the ListBox to MultiSimple if you
want to allow users to select multiple items for removal.

Example Code Snippet (Add and Remove Button Click Events):

VB.Net
' Add Button Click Event Handler
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
Dim newItem As String
If Not String.IsNullOrEmpty(txtNewItem.Text) Then ' Check if TextBox has
text
newItem = txtNewItem.Text
lstItems.Items.Add(newItem)
txtNewItem.Text = "" ' Clear the TextBox after adding
Else
MessageBox.Show("Please enter an item to add.", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

' Remove Button Click Event Handler


Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles
btnRemove.Click
If lstItems.SelectedIndex >= 0 Then
lstItems.Items.RemoveAt(lstItems.SelectedIndex)
Else
MessageBox.Show("Please select an item to remove.", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Use code with caution.
Additional Considerations:

 You can pre-populate the ListBox with items during form load using a loop to add
them programmatically.
 The ListBox allows you to access and manipulate selected items using its
SelectedIndex and SelectedItem properties.
 You can customize the appearance of the ListBox by setting properties like
ForeColor, BackColor, and Font.

This design demonstrates basic functionalities of a ListBox control in VB.Net. You can
extend it further based on your specific needs.

19. Design a Restaurant Bill.

Here's a simple VB.NET Windows Forms application for generating a restaurant bill:

Form Design:

1. Create a new Windows Forms application.


2. Add the following controls to the form:
o Labels:
 lblRestaurantName (Label to display restaurant name)
 lblItemName (Label for item name)
 lblQuantity (Label for quantity)
 lblPrice (Label for unit price)
 lblSubtotal (Label to display subtotal)
 lblTaxRate (Label for tax rate)
 lblTaxAmount (Label to display tax amount)
 lblTotal (Label to display total bill amount)
o Text Boxes:
 txtItemName (TextBox to enter item name)
 txtQuantity (TextBox to enter quantity)
 txtPrice (TextBox to enter unit price)
o Buttons:
 btnAdd (Button to add an item to the bill)
 btnClear (Button to clear all input fields)
 btnExit (Button to exit the application)
o List Box:
 lstBillItems (List box to display ordered items with quantity and price)

Code Behind (Form1.vb):

VB.Net

Public Class Form1

Private subTotal As Decimal = 0


Private taxRate As Decimal = 0.1 ' Adjust tax rate as needed
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set initial values (optional)
lblRestaurantName.Text = "Your Restaurant Name"
txtPrice.Enabled = False ' Disable price input (optional)
End Sub

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click


Dim itemName As String = txtItemName.Text.Trim()
Dim quantity As Integer = Integer.Parse(txtQuantity.Text.Trim())
Dim price As Decimal = Decimal.Parse(txtPrice.Text.Trim())

' Add validation checks for empty fields (optional)

Dim itemTotal As Decimal = quantity * price


subTotal += itemTotal

lstBillItems.Items.Add($"{quantity}x {itemName} ({price:C}) - {itemTotal:C}")

' Clear input fields


txtItemName.Text = ""
txtQuantity.Text = ""
End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click


lstBillItems.Items.Clear()
subTotal = 0
UpdateBillAmounts()
End Sub

Private Sub UpdateBillAmounts()


Dim taxAmount As Decimal = subTotal * taxRate
Dim total As Decimal = subTotal + taxAmount

lblSubtotal.Text = subTotal.ToString("C")
lblTaxRate.Text = (taxRate * 100).ToString("P") ' Display tax rate as percentage
lblTaxAmount.Text = taxAmount.ToString("C")
lblTotal.Text = total.ToString("C")
End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click


Me.Close() ' Close the application
End Sub
End Class
Use code with caution.

Explanation:

1. The code defines variables for subTotal and taxRate.


2. The Form1_Load event sets the initial restaurant name and disables the price input
field (optional).
3. The btnAdd_Click event adds an item to the bill:
o Retrieves item name, quantity, and price.
o Calculates the item total (quantity * price).
o Updates the subTotal variable.
o Adds a formatted string to the lstBillItems list box showing quantity, item
name, price, and item total.
o Clears input fields.
4. The btnClear_Click event clears the list box, resets subTotal, and updates bill
amounts.
5. The UpdateBillAmounts method calculates and displays tax amount, tax rate (as
percentage), and total bill amount based on subTotal and taxRate.
6. The btnExit_Click event closes the application.

Customization:

 You can modify the UI layout and add more controls as needed.
 Enhance the code with error handling for invalid input.

20. Design a splash screen.

Here's a VB.Net Windows Forms application design for a splash screen with code:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. In the toolbox, find and drag a Form control onto the designer.
3. Set the properties of the form as follows:
o WindowState: Set to Normal to prevent accidental resizing.
o ShowInTaskbar: Set to False to prevent it from appearing in the taskbar.
o TopMost: Set to True to display it on top of other windows.
o FormBorderStyle: Set to None to remove the title bar and borders.
o Size the form to your desired splash screen dimensions.
4. Add the following controls to the form:
o A PictureBox control to display an image (e.g., your application logo).
o A Label control (optional) to display application name or version information.
o A ProgressBar control (optional) to simulate loading progress (consider
using a timer to update its value).

Code Implementation:

1. In the form's code-behind file, add a timer to control the splash screen display
duration.

VB.Net
Public Class SplashScreenForm
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles
Timer1.Tick
' Simulate loading for a few seconds (adjust as needed)
If Me.Opacity < 1 Then
Me.Opacity += 0.1
Else
Timer1.Enabled = False
' Close the splash screen and open the main form
Me.Close()
' Replace with your main form instance
Dim mainForm As New MainForm
mainForm.Show()
End If
End Sub

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


Handles MyBase.Load
' Set initial opacity (can be adjusted for transparency)
Me.Opacity = 0.8
Timer1.Enabled = True ' Start the timer
End Sub

End Class
Use code with caution.

2. In the Main method of your project (usually in Form1.vb or Program.vb), display the
splash screen before launching the main application form:

VB.Net
' In your Main method (e.g., Form1.vb or Program.vb)
Dim splashForm As New SplashScreenForm
splashForm.Show()
Application.Run()
Use code with caution.

Additional Considerations:

 You can add animations or effects to the splash screen using the form's Opacity
property or by creating custom animations.
 Use appropriate image formats for the splash screen image (e.g., PNG for
transparency).
 Consider the target application's branding and overall user experience when designing
the splash screen.

This design provides a basic structure for creating a splash screen in VB.Net. You can
customize it to match your application's style and incorporate more advanced features if
desired.

21. Design an application to prepare student result.

Here's a VB.Net console application design to prepare student results with functionalities like
entering student data, calculating grades, and displaying the report:

Data Structures:
 Define a Student class to store student information:

VB.Net
Public Class Student
Public Property Name As String
Public Property Marks As List(Of Integer) ' List to store marks for
multiple subjects

' Function to calculate total marks (assuming all subjects have the same
weight)
Public Function GetTotalMarks() As Integer
Dim total As Integer = 0
For mark As Integer In Marks
total += mark
Next
Return total
End Function

' Function to calculate grade (assuming a basic grading system)


Public Function GetGrade() As String
Dim totalMarks = GetTotalMarks()
If totalMarks >= 90 Then
Return "A"
ElseIf totalMarks >= 80 Then
Return "B"
ElseIf totalMarks >= 70 Then
Return "C"
ElseIf totalMarks >= 60 Then
Return "D"
Else
Return "F"
End If
End Function
End Class
Use code with caution.

Code Implementation:

1. Create a console application project in Visual Studio.


2. In the Main method, implement the following functionalities:
o Student Data Input:
 Use a loop to allow the user to enter data for multiple students (name
and marks for each subject).
 Store the data in Student objects and add them to a list.
o Result Calculation:
 Loop through the list of Student objects.
 For each student, calculate the total marks using the GetTotalMarks
function of the Student class.
 Calculate the grade using the GetGrade function of the Student class.
o Report Generation:
 Display a formatted report header for the student results.
 Loop through the list of Student objects again.
 For each student, display their name, total marks, and grade in a well-
formatted table-like manner.
Example Code Snippet (Main Method):

VB.Net
Module Module1

Sub Main()
Dim students As New List(Of Student)

' Loop to get data for multiple students


Do While True
Console.WriteLine("Enter student name (or 'q' to quit): ")
Dim name As String = Console.ReadLine()
If name.ToLower = "q" Then Exit Do

' Get marks for each subject (assuming a fixed number of subjects)
Dim marks As New List(Of Integer)
For i As Integer = 1 To 3 ' Assuming 3 subjects
Console.WriteLine("Enter mark for subject {0}: ", i)
marks.Add(Integer.Parse(Console.ReadLine()))
Next

' Create a Student object and add it to the list


Dim student As New Student
student.Name = name
student.Marks = marks
students.Add(student)
Loop

' Display report header


Console.WriteLine("----------------------------------------")
Console.WriteLine("| Name | Total Marks | Grade |")
Console.WriteLine("----------------------------------------")

' Loop through students and display results


For Each student In students
Console.WriteLine("|{0,-15} | {1,11} | {2,8} |", student.Name,
student.GetTotalMarks(), student.GetGrade())
Next

Console.WriteLine("----------------------------------------")
Console.WriteLine("Press any key to close...")
Console.ReadKey()
End Sub

End Module
Use code with caution.

Additional Considerations:

 You can enhance the application by:


o Implementing error handling for invalid user input.
o Allowing users to specify the number of subjects and their weights for a more
flexible grading system.
o Saving the student results to a text file or database for future reference.
 Remember to modify the code based on your specific grading system and desired
functionalities.
Design the form to input electricity unit and calculate total electricity bill according to the
given condition

Unit Charge (Rs/unit)


For first 50 unit 0.50/unit
For first 100 unit 0.75/unit
For first 100 unit 1.2/unit
An additional surcharge of 20% is added to the bill
This approach utilizes custom classes and functions to structure the student data and result
calculations. You can adapt it further to create a more user-friendly and comprehensive
student result preparation application.

22.

Here's the design for a form to input electricity units and calculate the total electricity bill in
VB.Net:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o Two TextBox controls:
 One for entering the number of units consumed (e.g., txtUnits).
o Two Label controls:
 One to display "Units Consumed:" (e.g., lblUnits).
 One to display the calculated total bill amount (e.g., lblTotalBill).
o A Button control to calculate the bill (e.g., btnCalculate).

Code Implementation:

1. Double-click the "Calculate Bill" button to create an event handler for the Click
event.
2. In the code for the button's Click event handler:
o Get the number of units consumed from the txtUnits textbox (Dim units As
Integer = Integer.Parse(txtUnits.Text)).
o Implement the bill calculation logic:
 Define slab limits and charges per unit for each slab (e.g., slabLimits
= {50, 150}, slabRates = {0.5, 0.75, 1.2}).
 Initialize variables to accumulate bill amount and remaining units (Dim
billAmount As Double = 0.0, remainingUnits As Integer =
units).
 Use a loop to iterate through the slab limits:
 Calculate the amount for the current slab based on remaining
units and slab rate.
 Update the bill amount and remaining units for the next slab.
 After the loop, calculate the surcharge (20% of the bill amount).
 Add the surcharge to the bill amount.
o Display the calculated total bill amount in the lblTotalBill label
(lblTotalBill.Text = billAmount.ToString("0.00")).

Example Code Snippet (Button Click Event Handler):

VB.Net
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles
btnCalculate.Click
Dim units As Integer = Integer.Parse(txtUnits.Text)
Dim billAmount As Double = 0.0
Dim remainingUnits As Integer = units

' Define slab limits and charges per unit (modify as needed)
Dim slabLimits As Integer() = {50, 150}
Dim slabRates As Double() = {0.50, 0.75, 1.20} ' Add a rate for the last
slab limit

' Calculate bill amount based on slabs


For i As Integer = 0 To slabLimits.Length - 1
If remainingUnits <= 0 Then Exit For ' No units left for calculation
If remainingUnits > slabLimits(i) Then
billAmount += slabLimits(i) * slabRates(i)
remainingUnits -= slabLimits(i)
Else
billAmount += remainingUnits * slabRates(i)
remainingUnits = 0
End If
Next

' Calculate and apply surcharge (20%)


Dim surcharge = billAmount * 0.20
billAmount += surcharge

' Display total bill amount


lblTotalBill.Text = billAmount.ToString("0.00")
End Sub
Use code with caution.

Additional Considerations:

 You can add input validation to ensure the user enters a valid number of units.
 Consider improving the user interface with features like:
o Displaying a breakdown of the bill amount by slab.
o Formatting the input and output for better readability (e.g., currency symbols).
This design provides a basic structure for calculating the electricity bill based on slabs and
surcharge. You can customize it further to match your specific requirements and desired
functionalities.

23. Design windows form for MCQ examination.

Here's a Windows Form design for an MCQ examination in VB.Net:

Form Elements:

1. Question Panel (GroupBox):


o A Label control to display the question text.
o A GroupBox control (optional) to group multiple answer choices.
o Several RadioButton controls, each representing an answer choice (at least 2).
2. Navigation Panel:
o Two buttons:
 "Next" button to navigate to the next question.
 (Optional) "Previous" button to navigate to the previous question
(consider disabling it for the first question).
o A Label control (optional) to display the current question number and total
number of questions (e.g., "Question 1 / 10").
3. Result Panel (GroupBox - Optional):
o A Button control to submit the exam (disabled initially).
o A Label control (optional) to display the exam result after submission.

Code Implementation:

1. Define a class or structure to store question data (question text and answer choices).
2. Load the exam questions and answer choices from a data source (e.g., file, database)
into a list or array during form load.
3. Implement logic to navigate through the questions:
o Initially, display the first question and answer choices.
o When the "Next" button is clicked:
 Check if there are more questions. If yes, display the next question and
answer choices.
 If it's the last question, enable the "Submit" button (if applicable).
o (Optional) When the "Previous" button is clicked:
 Check if it's not the first question. If yes, display the previous question
and answer choices.
4. Implement logic for submitting the exam (optional Result Panel):
o When the "Submit" button is clicked:
 Evaluate the selected answers for each question (check which
RadioButton is selected).
 Calculate the score based on correct answers.
 Display the exam result (e.g., number of correct answers, score
percentage).

Additional Considerations:
 Use descriptive variable names and comments to improve code readability.
 Consider implementing a timer to limit the exam duration.
 You can enhance the user interface with features like:
o A progress bar to indicate the exam progress.
o The ability to review answered questions before submission.
o Shuffling the order of answer choices for each question.

Example Code Snippet (Question Navigation - Simplified):

VB.Net
Private questions As List(Of Question) ' List to store exam questions
Private currentQuestionIndex As Integer = 0 ' Index of the current question

' Function to display the current question and answer choices


Private Sub DisplayQuestion()
lblQuestion.Text = questions(currentQuestionIndex).Text ' Set question
text
' Loop through answer choices and set RadioButton properties
For i As Integer = 0 To questions(currentQuestionIndex).Choices.Count - 1
RadioButton controls... (set text and other properties based on answer
choices)
Next
Update navigation button states (enable/disable Next/Previous)
End Sub

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


btnNext.Click
If currentQuestionIndex < questions.Count - 1 Then
currentQuestionIndex += 1
DisplayQuestion()
End If
End Sub
Use code with caution.

This is a basic structure, and you can customize it further based on your specific exam
requirements and desired features. Remember to implement answer evaluation and result
display logic for a complete examination application.

24. Create a vb application that lets the user decide the width and height of a shape using
scroll bar control.

Here's a VB.Net Windows Forms application that lets the user decide the width and height of
a rectangle using scrollbar controls:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o A Panel control to draw the rectangle.
o Two HScrollBar controls (horizontal scrollbars) for width and height
adjustment:
 One labeled "Width" (e.g., hScrollBarWidth).
 One labeled "Height" (e.g., hScrollBarHeight).
o Two Label controls to display the current width and height values (e.g.,
lblWidth, lblHeight).

Code Implementation:

1. In the form class, define variables to store the current width and height of the
rectangle.
2. Implement event handlers for the ValueChanged events of both scrollbars:
o In each event handler:
 Get the new value from the scrollbar.
 Update the corresponding width or height variable.
 Invalidate the Panel control to trigger a repaint event.
3. Override the OnPaint method of the form class to draw the rectangle based on the
current width and height values.

Example Code Snippet:

VB.Net
Public Class Form1

Private width As Integer = 50 ' Initial width


Private height As Integer = 50 ' Initial height

Private Sub hScrollBarWidth_ValueChanged(sender As Object, e As


EventArgs) Handles hScrollBarWidth.ValueChanged
width = hScrollBarWidth.Value
lblWidth.Text = "Width: " & width.ToString()
Me.Invalidate() ' Invalidate Panel to trigger repaint
End Sub

Private Sub hScrollBarHeight_ValueChanged(sender As Object, e As


EventArgs) Handles hScrollBarHeight.ValueChanged
height = hScrollBarHeight.Value
lblHeight.Text = "Height: " & height.ToString()
Me.Invalidate() ' Invalidate Panel to trigger repaint
End Sub

Protected Overrides Sub OnPaint(e As PaintEventArgs)


MyBase.OnPaint(e)
e.Graphics.FillRectangle(Brushes.LightBlue, New Rectangle(100, 100,
width, height)) ' Draw rectangle with adjusted width and height
End Sub
End Class
Use code with caution.

Additional Considerations:

 You can set the minimum and maximum values for the scrollbars to restrict the
rectangle's size.
 Implement error handling to prevent the user from setting invalid values (e.g.,
negative width or height).
 Consider adding additional features like:
o The ability to change the rectangle's color.
o A button to reset the width and height to default values.

This design demonstrates how to use scrollbars to control the dimensions of a shape drawn on
a panel. You can extend it further based on your desired functionalities and visual effects.

25. Develop an application which is similar to notepad using menus.

Here's a VB.Net Windows Forms application similar to notepad using menus:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o A large multiline RichTextBox control for entering and editing text.

Menu Implementation:

1. Go to the menu bar at the top of the form design window.


2. Click "Design" and select "New Menu..."
3. In the "New Menu" dialog, name the menu "File" and click "OK".
4. Repeat steps 2 and 3 to create additional menus named "Edit" and "Help" (optional).

Code Implementation:

1. Double-click on the "File" menu in the designer to access its event handler code.
2. Add menu items for desired functionalities:
o New: Clear the RichTextBox content.
o Open: Use an OpenFileDialog control to allow users to open a text file and
load its content into the RichTextBox.
o Save: Use a SaveFileDialog control to allow users to save the RichTextBox
content to a text file.
o Exit: Close the application.
3. Implement similar logic for the "Edit" menu (optional):
o Undo/Redo: Utilize built-in RichTextBox functionality for undo/redo (if
supported by your RichTextBox control version).
o Cut/Copy/Paste: Implement functionalities using clipboard operations.
o Select All: Select all text in the RichTextBox.
4. Implement the "Help" menu (optional):
o About: Display a simple message box with information about the application.

Example Code Snippet (File Menu Items - Click Events):

VB.Net
' New menu item click event handler
Private Sub newMenuItem_Click(sender As Object, e As EventArgs) Handles
newMenuItem.Click
RichTextBox1.Text = "" ' Clear the RichTextBox content
End Sub
' Open menu item click event handler
Private Sub openMenuItem_Click(sender As Object, e As EventArgs) Handles
openMenuItem.Click
Dim openFileDialog As New OpenFileDialog
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
If openFileDialog.ShowDialog() = DialogResult.OK Then
RichTextBox1.Text = File.ReadAllText(openFileDialog.FileName)
End If
End Sub

' Save menu item click event handler (similar logic for Save As)
Private Sub saveMenuItem_Click(sender As Object, e As EventArgs) Handles
saveMenuItem.Click
Dim saveFileDialog As New SaveFileDialog
saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
If saveFileDialog.ShowDialog() = DialogResult.OK Then
File.WriteAllText(saveFileDialog.FileName, RichTextBox1.Text)
End If
End Sub
Use code with caution.

Additional Considerations:

 Use descriptive variable names and comments to improve code readability.


 Consider adding features like:
o Font selection for the text.
o Find and replace functionality.
o Word wrap and line numbering options.
 Implement error handling for file operations (opening and saving).

This design provides a basic structure for a notepad-like application in VB.Net. You can
expand it further based on desired functionalities and a more user-friendly interface.

26. Develop an application using font dialog control.

Here's a VB.Net Windows Forms application that utilizes a FontDialog control to allow users
to change the font style of their text:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o A large multiline RichTextBox control for entering and editing text.
o A Button control labeled "Change Font" (e.g., btnChangeFont).
3. In the toolbox, find the FontDialog control and add it to the form (it won't be visible
at runtime).

Code Implementation:

1. Double-click the "Change Font" button to access its click event handler code.
2. In the button's click event handler:
o Create an instance of the FontDialog control (Dim fontDialog As New
FontDialog).
o Set the ShowColor property of the FontDialog to True to allow users to
change the font color as well (optional).
o Use the ShowDialog method of the FontDialog to display the font selection
dialog (If fontDialog.ShowDialog = DialogResult.OK Then).
o If the user clicks "OK" in the font dialog:
 Update the font properties of the RichTextBox with the user's selection
(RichTextBox1.Font = fontDialog.Font).

Example Code Snippet (Button Click Event Handler):

VB.Net
Private Sub btnChangeFont_Click(sender As Object, e As EventArgs) Handles
btnChangeFont.Click
Dim fontDialog As New FontDialog
fontDialog.ShowColor = True ' Allow color selection (optional)

If fontDialog.ShowDialog = DialogResult.OK Then


RichTextBox1.Font = fontDialog.Font ' Apply selected font
End If
End Sub
Use code with caution.

Additional Considerations:

 You can add functionalities like:


o Saving and loading font preferences for future use.
o Applying the font change to selected text only (using RichTextBox selection
methods).
o A preview window in the font dialog to visualize font changes before
applying.

This design demonstrates using the FontDialog control to modify the font style and color of
text in a RichTextBox. You can customize it further to enhance the user experience and
incorporate additional font-related features.

27. Develop an application using color dialog control.

Here's a VB.Net Windows Forms application that utilizes a ColorDialog control to allow
users to change the text and background color of a label:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o A Label control to display text (e.g., lblText).
o Two Button controls:
 One labeled "Change Text Color" (e.g., btnTextColor).
 One labeled "Change Background Color" (e.g.,
btnBackgroundColor).
3. In the toolbox, find the ColorDialog control and add it to the form (it won't be visible
at runtime).

Code Implementation:

1. Double-click each button ("Change Text Color" and "Change Background Color") to
access their click event handler code.
2. In the button click event handlers:
o Create an instance of the ColorDialog control (Dim colorDialog As New
ColorDialog).
o Use the ShowDialog method of the ColorDialog to display the color selection
dialog (If colorDialog.ShowDialog = DialogResult.OK Then).
o If the user clicks "OK" in the color dialog:
 For "Change Text Color" button: Update the ForeColor property of
the Label with the user's selection (lblText.ForeColor =
colorDialog.Color).
 For "Change Background Color" button: Update the BackColor
property of the Label with the user's selection (lblText.BackColor =
colorDialog.Color).

Example Code Snippet (Button Click Event Handlers):

VB.Net
' Change Text Color button click event handler
Private Sub btnTextColor_Click(sender As Object, e As EventArgs) Handles
btnTextColor.Click
Dim colorDialog As New ColorDialog
If colorDialog.ShowDialog = DialogResult.OK Then
lblText.ForeColor = colorDialog.Color
End If
End Sub

' Change Background Color button click event handler (similar logic)
Private Sub btnBackgroundColor_Click(sender As Object, e As EventArgs)
Handles btnBackgroundColor.Click
Dim colorDialog As New ColorDialog
If colorDialog.ShowDialog = DialogResult.OK Then
lblText.BackColor = colorDialog.Color
End If
End Sub
Use code with caution.

Additional Considerations:

 You can add functionalities like:


o Saving and loading preferred colors for future use.
o Changing the color of other controls on the form using the same approach.
o Predefining a set of color options for the user to choose from.
This design demonstrates using the ColorDialog control to modify the text and background
colors of a label control. You can extend it further to allow color changes for other controls
and incorporate user preferences.

28. Develop an application to change back color of any control (label, textbox) using
scroll box.

Here's a VB.Net Windows Forms application that allows you to change the back color of any
control (label, textbox, etc.) using scrollbars:

Form Design:

1. Open Visual Studio and create a new Windows Forms Application project.
2. Add the following controls to the form:
o A GroupBox control to group the selection elements (optional).
o Several controls you want to allow color change for (e.g., a Label named
lblText, a TextBox named txtInput).
o Three HScrollBar controls (horizontal scrollbars) for red, green, and blue
color components:
 One labeled "Red" (e.g., hScrollBarRed).
 One labeled "Green" (e.g., hScrollBarGreen).
 One labeled "Blue" (e.g., hScrollBarBlue).
o A button to apply the selected color (e.g., btnApplyColor).

Code Implementation:

1. In the form class, define a variable to store the currently selected control (Dim
selectedControl As Control).
2. Implement an event handler for the Click event of any control you want to allow
color change for (e.g., lblText_Click, txtInput_Click). In each event handler:
o Set the selectedControl variable to the clicked control.
3. Implement event handlers for the ValueChanged event of each scrollbar:
o In each event handler:
 Get the new value from the scrollbar.
 Define a Color variable to store the combined red, green, and blue
values.
 Update the appropriate color component (Red, Green, or Blue) based
on the scrollbar that changed.
 Set the BackColor property of the selectedControl to the newly
created Color.
4. Implement an event handler for the Click event of the "Apply Color" button:
o Check if a control is selected (If selectedControl Is Nothing Then
Exit Sub).
o Apply the current scrollbar values (combined color) to the selectedControl's
BackColor property.

Example Code Snippet:


VB.Net
Public Class Form1

Private selectedControl As Control = Nothing ' Currently selected control

' Event handler for control clicks (set selectedControl)


Private Sub lblText_Click(sender As Object, e As EventArgs) Handles
lblText.Click
selectedControl = lblText
End Sub

' (Similar event handlers for other controls)

' Event handler for scrollbar value change (update color components)
Private Sub hScrollBarRed_ValueChanged(sender As Object, e As EventArgs)
Handles hScrollBarRed.ValueChanged
Dim newColor As Color = selectedControl.BackColor ' Get current control
color
newColor = Color.FromArgb(hScrollBarRed.Value, newColor.G, newColor.B)
' Update red component
selectedControl.BackColor = newColor
End Sub

' (Similar event handlers for green and blue scrollbars)

' Apply color button click event handler


Private Sub btnApplyColor_Click(sender As Object, e As EventArgs) Handles
btnApplyColor.Click
If selectedControl Is Nothing Then Exit Sub ' No control selected

Dim newColor As Color = Color.FromArgb(hScrollBarRed.Value,


hScrollBarGreen.Value, hScrollBarBlue.Value)
selectedControl.BackColor = newColor
End Sub
End Class
Use code with caution.

Additional Considerations:

 You can set the minimum and maximum values for the scrollbars (typically 0 to 255
for color components).
 Implement error handling to prevent unexpected behavior if a control is not selected.
 Consider adding labels to display the current red, green, and blue values.

This design allows you to dynamically change the back color of any selected control on the
form using scrollbars for each color component. You can customize it further based on your
desired color selection method and visual elements.

29. Write a program to calculate the discount according to the condition and display the
output as per format.
List Price Rate Of Discount
1) Upto rs. 2000 No Discount
2) From rs 2000 to rs 5000 discount 10%
3) From rs 5000 to rs 10000 Discount 15%
Up above rs 10000 Discount 20%
Here's the VB.Net program to calculate the discount based on the list price and display the
output in the desired format:

VB.Net
Module Module1

' Function to calculate discount based on price and discount rate


Function CalculateDiscount(price As Double, discountRate As Double) As
Double
Return price * discountRate
End Function

Sub Main()
Dim listPrice As Double

' Get list price from user


Console.WriteLine("Enter the list price: ")
If Double.TryParse(Console.ReadLine(), listPrice) Then

' Define discount rates for different price ranges


Dim discountRates = New Dictionary(Of Double, Double)() With {
{2000, 0},
{5000, 0.1},
{10000, 0.15},
{Double.MaxValue, 0.2} ' Any price above 10000 gets 20% discount
}

' Find the applicable discount rate based on the price


Dim applicableRate As Double = 0
For pair In discountRates
If price <= pair.Key Then
applicableRate = pair.Value
Exit For ' Exit loop after finding the first matching rate
End If
Next

' Calculate discount amount


Dim discountAmount = CalculateDiscount(listPrice, applicableRate)

' Calculate final price


Dim finalPrice = listPrice - discountAmount

' Display output in the desired format


Console.WriteLine("List
Price Rate Of
Discount")

Console.WriteLine("{0:0.00}
{1:0.0%}", listPrice, applicableRate)

Console.WriteLine("Discount
{0:0.00}", discountAmount)
Console.WriteLine("Final
Price {0:0.00}",
finalPrice)
Else
Console.WriteLine("Invalid price entered. Please enter a number.")
End If
Console.ReadLine() ' Wait for user to press Enter before closing
End Sub

End Module
Use code with caution.

Explanation:

1. The CalculateDiscount function takes the price and discount rate as arguments and
returns the discount amount.
2. The Main sub starts by prompting the user for the list price.
3. It defines a dictionary named discountRates to map price ranges to discount rates.
4. A loop iterates through the discountRates dictionary to find the applicable discount
rate based on the list price. The first matching rate is used.
5. The CalculateDiscount function is called to calculate the discount amount based on
the list price and applicable rate.
6. The final price is calculated by subtracting the discount amount from the list price.
7. The output is displayed in the desired format using console formatting options.

Improvements:

 This code uses a dictionary for discount rates, making it easier to add or modify
discount rules.
 It includes error handling to check for invalid price input.

30. Write a program in VB.Net to implement encapsulation in class.

Here's a VB.Net program demonstrating encapsulation in a class:

VB.Net
Public Class Product

' Private member variable to store product name


Private _name As String

' Public property with Get and Set accessors for product name
Public Property Name() As String
Get
Return _name
End Get
Set(value As String)
_name = value.Trim() ' Enforce trimming leading/trailing spaces
End Set
End Property

' Private member variable to store product price


Private _price As Double

' Public property with Get and Set accessors for product price
Public Property Price() As Double
Get
Return _price
End Get
Set(value As Double)
If value >= 0 Then ' Enforce non-negative price
_price = value
Else
Throw New ArgumentOutOfRangeException("Price cannot be negative.")
End If
End Set
End Property

' Public constructor to initialize product name and price


Public Sub New(name As String, price As Double)
Name = name ' Use the property setter for validation
Price = price ' Use the property setter for validation
End Sub

End Class

Module Module1

Sub Main()
Dim product1 As New Product("T-Shirt", 19.99)
Console.WriteLine("Product Name: {0}, Price: {1:0.00}", product1.Name,
product1.Price)

' Attempt to set invalid price (negative)


Try
product1.Price = -10.50
Catch ex As ArgumentOutOfRangeException
Console.WriteLine(ex.Message) ' Display error message
End Try

Console.ReadLine()
End Sub

End Module
Use code with caution.

Explanation:

1. The Product class defines private member variables to store product name (_name)
and price (_price).
2. Public properties are defined for Name and Price. These properties use Get and Set
accessors to control access and provide data validation.
3. The Name property setter trims leading and trailing spaces from the input value before
assigning it to the private variable.
4. The Price property setter enforces a non-negative price by throwing an
ArgumentOutOfRangeException if an invalid value is provided.
5. The constructor initializes the product name and price using the public properties
(which enforce validation).
6. The Main sub demonstrates creating a product object and accessing its properties.
7. It also attempts to set an invalid price (negative), which triggers the
ArgumentOutOfRangeException handled within a Try-Catch block.

This example showcases how encapsulation helps control data access, enforce data
validation, and improve code maintainability by separating data storage and manipulation
logic.
31. Write a program in VB.Net to demonstrate the concept of constructor and destructor.

Here's a VB.Net program demonstrating the concept of constructor and destructor:

VB.Net
Public Class Point

' Private member variables for point coordinates


Private _x As Integer
Private _y As Integer

' Public constructor to initialize point coordinates


Public Sub New(x As Integer, y As Integer)
_x = x
_y = y
Console.WriteLine("Point object created at {0} with coordinates ({1},
{2})", _hashCode, _x, _y) ' Include hash code for reference
End Sub

' Public method to display point coordinates


Public Sub Display()
Console.WriteLine("Point coordinates: ({0}, {1})", _x, _y)
End Sub

' Finalize method (destructor) - Not automatically called by garbage


collector in VB.Net
Protected Overrides Sub Finalize()
Console.WriteLine("Point object at {0} is being destroyed.", _hashCode)
MyBase.Finalize() ' Call base class Finalize (if applicable)
End Sub
End Class

Module Module1

Sub Main()
' Create a Point object
Dim point1 = New Point(3, 5)
point1.Display()

' Destructor won't be called automatically in VB.Net, unlike some other


languages.
' Simulate releasing the object using GC.Collect() but note this
' doesn't guarantee immediate destruction.
GC.Collect()

Console.WriteLine("Continuing with program execution...")


Console.ReadLine()
End Sub

End Module
Use code with caution.

Explanation:

1. The Point class defines private member variables _x and _y to store point
coordinates.
2. A public constructor New takes arguments for the x and y coordinates and initializes
the corresponding member variables.
3. The constructor also includes a message to the console that displays the object's hash
code and initial coordinates.
4. A public method Display allows displaying the point coordinates.
5. A protected override Finalize method is defined as the destructor. However, in
VB.Net, the garbage collector doesn't call the destructor automatically.
6. The Main sub creates a Point object and calls its Display method.
7. To simulate releasing the object (though not guaranteed destruction), GC.Collect is
called, but it might not trigger the destructor immediately.
8. The program continues execution to demonstrate that the object likely still exists in
memory until actual garbage collection occurs.

Note: While the code includes a Finalize method, it's important to remember that the
garbage collector in VB.Net doesn't rely on finalizers for object cleanup. You can remove the
Finalize method entirely for this example.

32. Create a class circle with data member radius; provide member function to calculate
area. Derive a class sphere from class circle; provide member function to calculate
volume. Derive class cylinder from class sphere with additional data member for
height and member function to calculate volume.

Here's the VB.Net code for the class hierarchy circle, sphere, and cylinder with member
functions to calculate their area and volume:

VB.Net
Public Class Circle
' Constant PI value
Public Const PI As Double = Math.PI

' Data member for radius


Private _radius As Double

' Public property for radius with validation


Public Property Radius() As Double
Get
Return _radius
End Get
Set(value As Double)
If value > 0 Then
_radius = value
Else
Throw New ArgumentOutOfRangeException("Radius must be positive.")
End If
End Set
End Property

' Constructor to initialize radius


Public Sub New(radius As Double)
Radius = radius ' Use property setter for validation
End Sub

' Member function to calculate circle area


Public Function CalculateArea() As Double
Return PI * Radius * Radius
End Function
End Class
Public Class Sphere
Inherits Circle

' Constructor to initialize sphere with radius


Public Sub New(radius As Double)
MyBase.New(radius) ' Call base class constructor
End Sub

' Member function to calculate sphere volume


Public Function CalculateVolume() As Double
Return (4 / 3) * Circle.PI * Radius * Radius * Radius
End Function
End Class

Public Class Cylinder


Inherits Sphere

' Data member for height


Private _height As Double

' Public property for height with validation


Public Property Height() As Double
Get
Return _height
End Get
Set(value As Double)
If value > 0 Then
_height = value
Else
Throw New ArgumentOutOfRangeException("Height must be positive.")
End If
End Set
End Property

' Constructor to initialize cylinder with radius and height


Public Sub New(radius As Double, height As Double)
MyBase.New(radius) ' Call base class constructor
Height = height ' Use property setter for validation
End Sub

' Member function to calculate cylinder volume


Public Function CalculateVolume() As Double
Return MyBase.CalculateVolume() + Circle.PI * Radius * Radius * Height
End Function

' Override base class CalculateVolume to avoid redundancy (optional)


' Public Overrides Function CalculateVolume() As Double
' Return (4 / 3) * Circle.PI * Radius * Radius * Radius + Circle.PI *
Radius * Radius * Height
' End Function
End Class

Module Module1

Sub Main()
Dim circle1 As New Circle(5)
Console.WriteLine("Circle area: {0:0.00}", circle1.CalculateArea())

Dim sphere1 As New Sphere(5)


Console.WriteLine("Sphere volume: {0:0.00}", sphere1.CalculateVolume())
Dim cylinder1 As New Cylinder(5, 10)
Console.WriteLine("Cylinder volume: {0:0.00}",
cylinder1.CalculateVolume())

Console.ReadLine()
End Sub

End Module
Use code with caution.

Explanation:

1. The Circle class defines a constant PI and a private member variable _radius.
2. A public property Radius with a setter enforces positive radius values.
3. The constructor initializes the radius using the property setter.
4. The CalculateArea function calculates the circle's area using PI and radius.
5. The Sphere class inherits from Circle and adds no new member variables.
6. The Sphere constructor calls the base class constructor to initialize the inherited
radius.
7. The CalculateVolume function for Sphere calculates the volume using the formula
for a sphere.
8. The Cylinder class inherits from Sphere and adds a data member _height.
9. A public property Height with a setter enforces a positive height value.
10. The Cylinder constructor calls the base class constructor to initialize the inherited
radius and sets its own height.
11. The CalculateVolume function for Cylinder calculates the total volume by adding
the sphere's volume (calling the base class function) and the volume of a cylinder on
top.
12. The Module1 demonstrates creating objects of each class and calling their member
functions.

This code implements inheritance effectively, with the Sphere class reusing the Circle
functionality and the Cylinder class further extending the Sphere behavior.

33. Write a simple ASP.NET program to display the following Web Controls:
1. A button with text “click me”. The button control must be in the center of
the form.
2. A label with a text hello
3.A checkbox.

Write a simple ASP.NET program to display the following


Web Controls: 1. A button with text “click me”. The
button control must be in the center of the form. 2. A
label with a text hello 3.A checkbox.
Show drafts
Here's an ASP.NET Web Forms program that displays a button, a label, and a checkbox with
the desired layout:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Simple Web Controls</title>
<style type="text/css">
.center-button {
text-align: center;
margin: 0 auto;
}
</style>
</head>
<body>
<form runat="server">
<div class="center-button">
<asp:Button ID="btnClickMe" runat="server" Text="Click Me" />
</div>
<br />
<asp:Label ID="lblHello" runat="server" Text="Hello" />
<asp:CheckBox ID="chkBox" runat="server" Text="Check Me" />
</form>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No code required in the Page_Load event for this simple example
}
}
Use code with caution.

Explanation:

1. The HTML code defines the basic structure of the page.


2. The <style> section defines a CSS class center-button to center the button
horizontally using text-align: center and margin: 0 auto.
3. The form element (<form runat="server">) allows server-side processing of form
elements.
4. The <div> element with the center-button class wraps the asp:Button control,
achieving the desired centering effect.
5. Below the button, separate lines display the asp:Label and asp:CheckBox controls
using their server-side IDs.
6. The code-behind file (Default.aspx.cs) doesn't require any specific code for this
example since there are no events being handled.

Running the Application:

1. Save the above code as Default.aspx and Default.aspx.cs in a new ASP.NET


Web Forms project.
2. Run the project and navigate to the default page (usually http://localhost:<port
number>/Default.aspx).
3. You should see the button centered on the form, the label displaying "Hello", and a
checkbox labeled "Check Me".

34. Write a ASP.NET program to display “Welcome To Radiant” in the form when the “click”
button is clicked.

Here's an ASP.NET Web Forms program that displays "Welcome To Radiant" in a label
when the "Click Me" button is clicked:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Welcome Message</title>
</head>
<body>
<form runat="server">
<asp:Button ID="btnClickMe" runat="server" Text="Click Me"
OnClick="btnClickMe_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text="" />
</form>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void btnClickMe_Click(object sender, EventArgs e)
{
lblMessage.Text = "Welcome To Radiant";
}

protected void Page_Load(object sender, EventArgs e)


{
// No code required in the Page_Load event for this functionality
}
}
Use code with caution.

Explanation:

1. The HTML code defines the button and label controls like the previous example.
2. The OnClick attribute of the asp:Button control is set to "btnClickMe_Click,"
referencing the event handler method in the code-behind file.
3. The code-behind file (Default.aspx.cs) defines two methods:
o Page_Load: This event handler is typically used to initialize the page on first
load. In this case, we don't need any code here.
o btnClickMe_Click: This method is triggered when the button is clicked.
Inside this method:
 We access the lblMessage label control using its server-side ID.
 We set the Text property of the label to "Welcome To Radiant."

Running the Application:

1. Save the above code as Default.aspx and Default.aspx.cs in a new ASP.NET


Web Forms project.
2. Run the project and navigate to the default page (usually http://localhost:<port
number>/Default.aspx).
3. Click the "Click Me" button. You should see the label displaying "Welcome To
Radiant."

35. Write an ASP.Net program to implement the email validation checking validation
controls.The form title must be ASP.NET.

Here's an ASP.NET Web Forms program that implements email validation using validation
controls and displays a form titled "ASP.NET":

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET</title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// Register client-side validation for better user experience
(optional)
this.ValidateRequestMode = ValidateRequestMode.Disabled;
}
</script>
</head>
<body>
<h1>ASP.NET</h1>
<form id="emailForm" runat="server" onsubmit="return
ValidateEmail(this)">
<asp:Label ID="lblEmail" runat="server" Text="Enter
Email:"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"
TextMode="Email"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Email is required." />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\w+@\w+\.\w+"
ErrorMessage="Invalid email format." />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:ValidationSummary ID="validationSummary" runat="server"
ShowMessageBox="True" />
</form>
</body>
<script type="text/javascript">
// Optional client-side validation function (improves user experience)
function ValidateEmail(form) {
if (!form.txtEmail.value.match(/\w+@\w+\.\w+/)) {
alert("Invalid email format!");
return false;
}
return true;
}
</script>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No additional code required in Page_Load for this example
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// This event handler would be triggered on server-side form
submission (if not using client-side validation)
// You could potentially perform additional email validation or
processing here.
}
}
Use code with caution.

Explanation:

1. The HTML code sets the title of the page to "ASP.NET" using the <h1> tag.
2. The form element includes:
o A label for "Enter Email:"
o A textbox (txtEmail) with TextMode="Email" (suggests email input to the
user).
o A RequiredFieldValidator (rfvEmail) to ensure an email is entered.
o A RegularExpressionValidator (revEmail) to validate the email format
using a regular expression (\w+@\w+\.\w+).
o A submit button (btnSubmit).
o A ValidationSummary control (validationSummary) to display any
validation errors in a message box.
3. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this case) disables request
validation to allow client-side validation using JavaScript.
o btnSubmit_Click: This event handler would be triggered on server-side form
submission (if client-side validation is disabled). However, it's commented out
here as we're relying on client-side validation for a better user experience.

Improvements:

 The code includes optional client-side validation using JavaScript to improve user
experience by providing immediate feedback on invalid email format.
 The server-side validation remains in place for complete validation even if JavaScript
is disabled.

Note: The provided regular expression for email validation is a basic example. More robust
email validation might involve stricter regular expressions or server-side verification with
email providers.

36. Write an ASP.Net program to implement the validation controls for equality
checking of password and repassword.

Here's an ASP.NET Web Forms program that implements validation controls for equality
checking of password and re-password:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Password Validation</title>
</head>
<body>
<h1>Register</h1>
<form id="registerForm" runat="server" onsubmit="return
ValidatePasswords(this)">
<asp:Label ID="lblPassword" runat="server"
Text="Password:"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server"
ControlToValidate="txtPassword" ErrorMessage="Password is required." />
<br />
<asp:Label ID="lblRePassword" runat="server" Text="Re-type
Password:"></asp:Label>
<asp:TextBox ID="txtRePassword" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvRePassword" runat="server"
ControlToValidate="txtRePassword" ErrorMessage="Re-type password is
required." />
<asp:CompareValidator ID="cvPasswords" runat="server"
ControlToCompare="txtPassword" ControlToValidate="txtRePassword"
Operator="Equal" ErrorMessage="Passwords do not match." />
<br />
<asp:Button ID="btnRegister" runat="server" Text="Register" />
<asp:ValidationSummary ID="validationSummary" runat="server"
ShowMessageBox="True" />
</form>

<script type="text/javascript">
// Optional client-side validation function (improves user
experience)
function ValidatePasswords(form) {
if (form.txtPassword.value !== form.txtRePassword.value) {
alert("Passwords do not match!");
return false;
}
return true;
}
</script>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No additional code required in Page_Load for this example
}

protected void btnRegister_Click(object sender, EventArgs e)


{
// This event handler would be triggered on server-side form
submission (if not using client-side validation)
// You could potentially perform additional password processing or
registration logic here.
}
}
Use code with caution.

Explanation:

1. The HTML code defines a registration form with labels and textboxes for password
and re-password.
2. It includes:
o RequiredFieldValidator controls for both password and re-password fields.
o A CompareValidator (cvPasswords) to compare the values of txtPassword
and txtRePassword. The Operator property is set to Equal to ensure they
match.
o A ValidationSummary control (validationSummary) to display any
validation errors in a message box.
3. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this case) doesn't require any code
here.
o btnRegister_Click: This event handler would be triggered on server-side
form submission (if client-side validation is disabled). However, it's
commented out here as we're relying on client-side validation for a better user
experience.

Improvements:

 The code includes optional client-side validation using JavaScript to improve user
experience by providing immediate feedback on mismatched passwords.
 The server-side validation remains in place for complete validation even if JavaScript
is disabled.

37. Write an ASP.Net program to implement the validation controls for checking value of
textbox control with date type value only.

Here's an ASP.NET Web Forms program that implements validation controls for checking
the value of a textbox control to ensure it contains a valid date:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Date Validation</title>
</head>
<body>
<h1>Enter Date</h1>
<form id="dateForm" runat="server" onsubmit="return
ValidateDate(this)">
<asp:Label ID="lblDate" runat="server" Text="Date (YYYY-MM-
DD):"></asp:Label>
<asp:TextBox ID="txtDate" runat="server"
InputType="Date"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDate" runat="server"
ControlToValidate="txtDate" ErrorMessage="Date is required." />
<asp:RegularExpressionValidator ID="revDate" runat="server"
ControlToValidate="txtDate" ValidationExpression="^\d{4}-\d{2}-\d{2}$"
ErrorMessage="Invalid date format (YYYY-MM-DD)." />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:ValidationSummary ID="validationSummary" runat="server"
ShowMessageBox="True" />
</form>

<script type="text/javascript">
// Optional client-side validation function (improves user
experience)
function ValidateDate(form) {
if (!form.txtDate.value.match(/^\d{4}-\d{2}-\d{2}$/)) {
alert("Invalid date format!");
return false;
}
return true;
}
</script>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No additional code required in Page_Load for this example
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// This event handler would be triggered on server-side form
submission (if not using client-side validation)
// You could potentially perform additional date parsing or
processing here.

try
{
// Attempt to convert the entered value to a DateTime object
for server-side validation
DateTime enteredDate = DateTime.Parse(txtDate.Text);
}
catch (FormatException)
{
validationSummary.HeaderText = "Error";
validationSummary.ErrorMessage = "Invalid date format (YYYY-MM-
DD).";
e.IsValid = false; // Mark validation as failed
}
}
}
Use code with caution.

Explanation:

1. The HTML code defines a form with a label and textbox for entering a date.
o The textbox (txtDate) has its InputType set to "Date" for user guidance.
2. It includes:
o A RequiredFieldValidator (rfvDate) to ensure a date is entered.
o A RegularExpressionValidator (revDate) to validate the date format using
a regular expression (^\d{4}-\d{2}-\d{2}$) that matches YYYY-MM-DD.
o A ValidationSummary control (validationSummary) to display any
validation errors in a message box.
3. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this case) doesn't require any code
here.
o btnSubmit_Click: This event handler would be triggered on server-side form
submission (if not using client-side validation). It includes:
 Optional client-side validation using JavaScript to improve user
experience.
 Server-side validation that attempts to parse the entered value
(txtDate.Text) into a DateTime object using DateTime.Parse. If
parsing fails (due to invalid format), it sets the validationSummary
control's properties to display an error message and marks the
validation as failed using e.IsValid = false.

Improvements:

 The code includes optional client-side validation using JavaScript to improve user
experience by providing immediate feedback on invalid date format.
 The server-side validation attempts to parse the entered value into a DateTime object

38. Write a program to get a user input such as the boiling point of water and test it to
the appropriate value using Compare Validator.

While using a CompareValidator control in ASP.NET Web Forms can be achieved, it's not
the most suitable approach for validating the boiling point of water. Here's why:

 Constant Value Comparison: CompareValidator compares the user input with a


constant value you define. The boiling point of water can vary slightly depending on
pressure.
 Limited Error Handling: CompareValidator only provides an error message if the
values don't match exactly. It doesn't allow for a range of acceptable values.

Here's a better approach using server-side validation in the code-behind file:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Boiling Point Validation</title>
</head>
<body>
<h1>Boiling Point of Water</h1>
<form id="boilingPointForm" runat="server" onsubmit="return
ValidateBoilingPoint(this)">
<asp:Label ID="lblBoilingPoint" runat="server" Text="Enter Boiling
Point (°C):"></asp:Label>
<asp:TextBox ID="txtBoilingPoint" runat="server"
Type="Number"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvBoilingPoint" runat="server"
ControlToValidate="txtBoilingPoint" ErrorMessage="Boiling point is
required." />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Label ID="lblResult" runat="server" Text=""
runat="server"></asp:Label>
</form>

<script type="text/javascript">
// Optional client-side validation function (improves user
experience)
function ValidateBoilingPoint(form) {
if (isNaN(form.txtBoilingPoint.value)) {
alert("Invalid input! Please enter a number.");
return false;
}
return true;
}
</script>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No additional code required in Page_Load for this example
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// Server-side validation and processing
double enteredBoilingPoint = double.Parse(txtBoilingPoint.Text);
double standardBoilingPoint = 100; // Standard boiling point of
water in °C (can be adjusted if needed)
double acceptableRange = 2; // Acceptable variation range in °C
(can be adjusted)

if (Math.Abs(enteredBoilingPoint - standardBoilingPoint) <=


acceptableRange)
{
lblResult.Text = "Correct! The boiling point of water is around
" + standardBoilingPoint + "°C.";
}
else
{
lblResult.Text = "The entered value (" + enteredBoilingPoint +
"°C) is outside the expected range for the boiling point of water
(approximately " + standardBoilingPoint + "°C ± " + acceptableRange +
"°C).";
}
}
}
Use code with caution.

Explanation:

1. The HTML code is similar to the previous example with a label and textbox for
entering a numeric boiling point value.
2. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this case) doesn't require any code
here.
o btnSubmit_Click: This event handler is triggered on form submission:
 It parses the entered boiling point (txtBoilingPoint.Text) into a
double value.
 It defines a standard boiling point (standardBoilingPoint) and an
acceptable variation range (acceptableRange).
 It uses an if statement to check if the absolute difference between the
entered value and the standard point is within the acceptable range.
 If it's within the range, a success message is displayed.
 Otherwise, an error message is displayed, indicating the entered
value is outside the expected range.

Improvements:

 This approach uses server-side validation to check if the entered value falls within an
acceptable range for the boiling point of water.
 You can adjust the standardBoilingPoint and `acceptable

39. Write a program that uses a textbox for a user input name and validate it for
RequiredField Validation.

Show drafts

Here's an ASP.NET Web Forms program that uses a textbox for user input of a name and
validates it using a RequiredFieldValidator:

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Name Validation</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form id="nameForm" runat="server">
<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName" ErrorMessage="Name is required." />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:ValidationSummary ID="validationSummary" runat="server"
ShowMessageBox="True" />
</form>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No additional code required in Page_Load for this example
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// This event handler would be triggered on server-side form
submission
// You could potentially use the entered name here (e.g., display a
greeting)
if (Page.IsValid) // Check if validation passed
{
string name = txtName.Text;
// Use the entered name (e.g., lblMessage.Text = "Hello, " +
name + "!")
}
}
}
Use code with caution.

Explanation:

1. The HTML code defines a form with a label and textbox for entering a name.
2. It includes a RequiredFieldValidator (rfvName) to ensure the user enters a name.
The ControlToValidate property specifies the textbox to validate.
3. A ValidationSummary control (validationSummary) displays any validation errors
in a message box.
4. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this sase) doesn't require any code
here.
o btnSubmit_Click: This event handler is triggered on form submission:
 It checks if the validation (Page.IsValid) passed using the
ValidationSummary control.
 If validation is successful, you can access the entered name through
txtName.Text. You can then use this name for processing or
displaying a message (commented out in the example).

40. Declare one TextBox control, one Button control, one Label control, and one
RegularExpressionValidator control in an .aspx file. The submit() function checks if the
page is valid. If it is valid, it returns "The page is valid!" in the Label control. If it is not
valid, it returns "The page is not valid!" in the Label control. If validation fails, the text
"The zip code must be 5 numeric digits!" will be displayed in
theRegularExpressionValidator control.

Here's the ASP.NET Web Forms code with the desired functionalities:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Zip Code Validation</title>
</head>
<body>
<h1>Enter Zip Code</h1>
<form id="zipCodeForm" runat="server" onsubmit="return ValidatePage()">
<asp:Label ID="lblZipCode" runat="server" Text="Zip
Code:"></asp:Label>
<asp:TextBox ID="txtZipCode" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvZipCode" runat="server"
ControlToValidate="txtZipCode" ErrorMessage="Zip code is required." />
<asp:RegularExpressionValidator ID="revZipCode" runat="server"
ControlToValidate="txtZipCode" ValidationExpression="^\d{5}$"
ErrorMessage="The zip code must be 5 numeric digits!" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</form>
<script type="text/javascript">
function ValidatePage() {
if (document.getElementById('zipCodeForm').checkValidity()) {
document.getElementById('lblResult').textContent = "The
page is valid!";
return true;
} else {
document.getElementById('lblResult').textContent = "The
page is not valid!";
return false;
}
}
</script>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No code required in Page_Load for this example
}
}
Use code with caution.

Explanation:

1. The HTML code defines the form elements:


o A label for "Zip Code:"
o A textbox (txtZipCode) for entering the zip code.
o A RequiredFieldValidator (rfvZipCode) to ensure a zip code is entered.
o A RegularExpressionValidator (revZipCode) to validate the zip code
format using a regular expression (^\d{5}$) that matches 5 numeric digits.
o A submit button (btnSubmit).
o A label (lblResult) to display the validation message.
2. The JavaScript function ValidatePage is triggered on form submission (using
onsubmit). It:
o Checks the form validity using
document.getElementById('zipCodeForm').checkValidity().
o Sets the text of lblResult based on the validation status.
o Returns true for valid forms and false for invalid forms. This return value is
used by the browser's default form submission behavior.
3. The code-behind file (Default.aspx.cs) doesn't require any specific code for this
example since the validation logic is handled in JavaScript.

Improvements:

 This approach uses JavaScript client-side validation for a better user experience by
providing immediate feedback on invalid zip code format.
 Server-side validation remains in place using ASP.NET validation controls for
additional security.

41. Check the length of the string in the TextBox using CustomValidator.

Here's an ASP.NET Web Forms program that uses a CustomValidator control to check the
length of the string in a TextBox:

HTML (Default.aspx):
HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>String Length Validation</title>
</head>
<body>
<h1>Enter Text</h1>
<form id="textForm" runat="server" onsubmit="return
ValidateTextLength()">
<asp:Label ID="lblText" runat="server" Text="Text:"></asp:Label>
<asp:TextBox ID="txtText" runat="server"
MaxLength="50"></asp:TextBox>
<asp:CustomValidator ID="cvTextLength" runat="server"
ControlToValidate="txtText" OnServerValidate="ValidateTextLengthServerSide"
ErrorMessage="Text length is outside the allowed range (1-50
characters)." />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:ValidationSummary ID="validationSummary" runat="server"
ShowMessageBox="True" />
</form>

<script type="text/javascript">
// Optional client-side validation function (improves user
experience)
function ValidateTextLength() {
var textLength =
document.getElementById('txtText').value.length;
if (textLength < 1 || textLength > 50) {
alert("Text length is outside the allowed range (1-50
characters).");
return false;
}
return true;
}
</script>
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// No code required in Page_Load for this example
}

protected void ValidateTextLengthServerSide(object source,


ServerValidateEventArgs args)
{
int minLength = 1;
int maxLength = 50; // Adjust these values as needed
int textLength = txtText.Text.Length;
args.IsValid = (textLength >= minLength) && (textLength <=
maxLength);
}
}
Use code with caution.

Explanation:

1. The HTML code defines the form elements:


o A label for "Text:"
o A textbox (txtText) with a maximum length of 50 characters set using
MaxLength.
o A CustomValidator control (cvTextLength) to validate the text length on the
server-side. It references the ValidateTextLengthServerSide method in the
code-behind.
o A submit button (btnSubmit).
o A ValidationSummary control (validationSummary) to display any
validation errors in a message box.
2. The client-side JavaScript function ValidateTextLength (optional) provides
immediate feedback on invalid text length. It checks if the text length is within the
allowed range (1-50 characters) and displays an alert if not.
3. The code-behind file defines two methods:
o Page_Load: This event handler (optional in this case) doesn't require any code
here.
o ValidateTextLengthServerSide: This method is triggered when the
CustomValidator control performs server-side validation:
 It defines the minimum and maximum allowed text lengths.
 It retrieves the actual text length from txtText.Text.Length.
 It sets the IsValid property of the ServerValidateEventArgs
argument based on whether the text length is within the defined range.

Improvements:

 This approach combines client-side validation using JavaScript for a better user
experience and server-side validation using a CustomValidator for enhanced
security.
 You can adjust the minLength and maxLength variables in the code-behind to define
the allowed text length range.

42. Create table STUDENT with the following columns and datatypes.
Sid Alphanumeric
Name Varchar(20)
DOB DateTime
Addr Varchar(20)
Contact Varchar(10)
1. Insert following records into the table:
Sid S1 S2 S3
Name OshoJuneja NishantSahni SanyaDua
DOB 28-jan-93 1-oct-92 30-jul-94
Addr ABC XYZ PQR
Contact 9000000000 8000000000 7800000000

ii) Select records from table where age>22.[Use DOB for age calculation].
iii) Count the record in the table.
Display records of the table order by DOB. In ASP.NET Perform using ADO.net

Here's the ASP.NET program using ADO.NET to perform the tasks you described:

C# Code (Default.aspx.cs):

C#
using System;
using System.Data;
using System.Data.SqlClient; // Replace with your database provider
namespace

public partial class Default : System.Web.UI.Page


{
private string connectionString = @"Data
Source=YOUR_SERVER_ADDRESS;Initial Catalog=YOUR_DATABASE_NAME;Integrated
Security=True"; // Replace with your connection string

protected void Page_Load(object sender, EventArgs e)


{
// Call methods for data manipulation and display results
InsertStudents();
DisplayStudentsByAge();
DisplayRecordCount();
DisplayStudentsByDob();
}

private void InsertStudents()


{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();

string insertQuery = @"


INSERT INTO STUDENT (Sid, Name, DOB, Addr, Contact)
VALUES (@Sid, @Name, @DOB, @Addr, @Contact)";

SqlCommand insertCommand = new SqlCommand(insertQuery,


connection);

insertCommand.Parameters.AddWithValue("@Sid", "S1");
insertCommand.Parameters.AddWithValue("@Name", "OshoJuneja");
insertCommand.Parameters.AddWithValue("@DOB",
DateTime.Parse("28-Jan-1993"));
insertCommand.Parameters.AddWithValue("@Addr", "ABC");
insertCommand.Parameters.AddWithValue("@Contact",
"9000000000");

insertCommand.ExecuteNonQuery();

// Repeat for other student records with appropriate parameter


values
connection.Close();
}
}

private void DisplayStudentsByAge()


{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();

string selectQuery = @"


SELECT * FROM STUDENT
WHERE DATEDIFF(YEAR, DOB, GETDATE()) > 22"; // Calculate
age using DATEDIFF

SqlCommand selectCommand = new SqlCommand(selectQuery,


connection);

SqlDataReader reader = selectCommand.ExecuteReader();

if (reader.HasRows)
{
lblResult.Text = "<b>Students older than 22
years:</b><br/>";
while (reader.Read())
{
lblResult.Text += $"Sid: {reader["Sid"]}, Name:
{reader["Name"]}, Age: {DateTime.Now.Year -
reader.GetDateTime(reader.GetOrdinal("DOB")).Year}<br/>";
}
}
else
{
lblResult.Text = "No students found older than 22 years.";
}

reader.Close();
connection.Close();
}
}

private void DisplayRecordCount()


{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();

string countQuery = "SELECT COUNT(*) FROM STUDENT";

SqlCommand countCommand = new SqlCommand(countQuery,


connection);

int recordCount = (int)countCommand.ExecuteScalar();

lblResult.Text += $"<br/><b>Total Students:</b> {recordCount}";

connection.Close();
}
}

private void DisplayStudentsByDob()


{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();

string selectQuery = "SELECT * FROM STUDENT ORDER BY DOB";

SqlCommand selectCommand = new SqlCommand(selectQuery,


connection);

SqlDataReader reader = selectCommand.ExecuteReader();

if (reader.HasRows)
{
lblResult.Text += "<br/><b>Students ordered by
DOB:</b><br/>";
while (reader.Read())
{
lblResult.Text += $"Sid: {reader["Sid"]}, Name:
{reader["Name"]}, DOB:
{reader.GetDateTime(reader.GetOrdinal("DOB"))}<br/>";
}
}
else
{
lblResult.Text += "<br/>No students found in the table.";
}

reader.Close();
connection.Close();
}
}
}
Use code with caution.

Explanation:

1. Replace connectionString: Replace YOUR_SERVER_ADDRESS and


YOUR_DATABASE_NAME with your actual database server address and database name.
2. InsertStudents: This method creates a connection to the database, defines an INSERT
query with parameters, and inserts the provided student records. It repeats the
insertion for each student using appropriate parameter values.
3. **DisplayStudentsBy

43. Develop an application using the data reader to read from a database.

Here's an ASP.NET Web Forms application that demonstrates using a DataReader to read
data from a database:

HTML (Default.aspx):

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read Data with DataReader</title>
</head>
<body>
<h1>Student List</h1>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btnReadData" runat="server" Text="Read Data"
OnClick="ReadData_Click" />
</body>
</html>
Use code with caution.

Code Behind (Default.aspx.cs):

C#
using System;
using System.Data;
using System.Data.SqlClient; // Replace with your database provider
namespace

public partial class Default : System.Web.UI.Page


{
private string connectionString = @"Data
Source=YOUR_SERVER_ADDRESS;Initial Catalog=YOUR_DATABASE_NAME;Integrated
Security=True"; // Replace with your connection string

protected void Page_Load(object sender, EventArgs e)


{
// No code required in Page_Load for this example
}

protected void ReadData_Click(object sender, EventArgs e)


{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();

string selectQuery = "SELECT * FROM STUDENT"; // Replace with


your desired table name and columns

SqlCommand selectCommand = new SqlCommand(selectQuery,


connection);

SqlDataReader reader = selectCommand.ExecuteReader();

if (reader.HasRows)
{
lblResult.Text = "<b>Student Data:</b><br/>";
while (reader.Read())
{
// Access column values using reader["ColumnName"] or
reader.GetOrdinal("ColumnName")
lblResult.Text += $"Sid: {reader["Sid"]}, Name:
{reader["Name"]}, DOB:
{reader.GetDateTime(reader.GetOrdinal("DOB"))}<br/>";
}
}
else
{
lblResult.Text = "No data found in the table.";
}

reader.Close();
connection.Close();
}
}
}
Use code with caution.

Explanation:

1. Replace connectionString: Replace YOUR_SERVER_ADDRESS and


YOUR_DATABASE_NAME with your actual database server address and database name.
2. HTML: The HTML code defines a label (lblResult) to display the data retrieved
from the database.
3. ReadData_Click: This event handler is triggered when the "Read Data" button is
clicked.
o It creates a connection to the database using the connection string.
o It defines a SELECT query to retrieve data from the STUDENT table (replace with
your desired table name and columns).
o It creates a SqlCommand object with the query and connection.
o It executes the command using ExecuteReader to get a SqlDataReader.
o It checks if there are any rows (reader.HasRows).
 If rows exist, it iterates through them using while (reader.Read()).
 Inside the loop, it accesses column values using either
reader["ColumnName"] or
reader.GetOrdinal("ColumnName"). The latter provides
more performance for frequently accessed columns.
 It builds the output string with student details and displays it in
the lblResult label.
 If no rows are found, it displays a message in the label.
o Finally, it closes the SqlDataReader and the connection object.

Improvements:

 You can modify the SELECT query to retrieve specific columns or filter the data based
on conditions.
 Consider using error handling (try-catch block) to gracefully handle potential database
connection or execution issues.

44. Create following table Student(id, name, course, DOB, address)


Write vb.net application to
Add records
view all the records
Delete the particular record
View all the student who are studying in course MCA using DataSet.

Here's the VB.NET application using a DataSet to perform CRUD (Create, Read, Update,
Delete) operations and filter students by course on a Student table:

VB.Net
Imports System.Data.SqlClient

Partial Class Default


Inherits System.Web.UI.Page

Dim connectionString As String = "Data


Source=YOUR_SERVER_ADDRESS;Initial Catalog=YOUR_DATABASE_NAME;Integrated
Security=True" ' Replace with your connection string
Dim dsStudents As New DataSet

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles


Me.Load
' Load existing data on page load (optional)
LoadStudentData()
End Sub

Protected Sub btnAddStudent_Click(sender As Object, e As EventArgs)


Handles btnAddStudent.Click
Dim id As Integer = txtID.Text.Trim().ToInt32()
Dim name As String = txtName.Text.Trim()
Dim course As String = txtCourse.Text.Trim()
Dim dob As DateTime = Date.Parse(txtDOB.Text.Trim())
Dim address As String = txtAddress.Text.Trim()

' Add validation checks for empty fields (optional)

Using connection As New SqlConnection(connectionString)


connection.Open()

Dim insertQuery As String = "INSERT INTO Student (ID, Name,


Course, DOB, Address) VALUES (@ID, @Name, @Course, @DOB, @Address)"
Dim insertCommand As New SqlCommand(insertQuery, connection)

insertCommand.Parameters.AddWithValue("@ID", id)
insertCommand.Parameters.AddWithValue("@Name", name)
insertCommand.Parameters.AddWithValue("@Course", course)
insertCommand.Parameters.AddWithValue("@DOB", dob)
insertCommand.Parameters.AddWithValue("@Address", address)

insertCommand.ExecuteNonQuery()

ClearTextBoxes() ' Clear input fields after insertion


LoadStudentData() ' Refresh data grid
End Using

lblMessage.Text = "Student record added successfully!"


End Sub

Protected Sub btnViewAll_Click(sender As Object, e As EventArgs)


Handles btnViewAll.Click
LoadStudentData()
End Sub
Protected Sub btnDeleteStudent_Click(sender As Object, e As EventArgs)
Handles btnDeleteStudent.Click
Dim id As Integer = txtID.Text.Trim().ToInt32()

Using connection As New SqlConnection(connectionString)


connection.Open()

Dim deleteQuery As String = "DELETE FROM Student WHERE ID =


@ID"
Dim deleteCommand As New SqlCommand(deleteQuery, connection)

deleteCommand.Parameters.AddWithValue("@ID", id)

Dim rowsDeleted As Integer = deleteCommand.ExecuteNonQuery()

If rowsDeleted > 0 Then


ClearTextBoxes()
LoadStudentData()
lblMessage.Text = "Student record deleted successfully!"
Else
lblMessage.Text = "No record found with the specified ID."
End If
End Using
End Sub

Protected Sub btnFilterByCourse_Click(sender As Object, e As EventArgs)


Handles btnFilterByCourse.Click
Dim course As String = txtFilterCourse.Text.Trim()

Using connection As New SqlConnection(connectionString)


connection.Open()

Dim selectQuery As String = "SELECT * FROM Student WHERE Course


= @Course"
Dim selectCommand As New SqlCommand(selectQuery, connection)

selectCommand.Parameters.AddWithValue("@Course", course)

Dim adapter As New SqlDataAdapter(selectCommand)


adapter.Fill(dsStudents, "Students") ' Fill a DataTable named
"Students" in the DataSet

GridView1.DataSource = dsStudents.Tables("Students") ' Bind


filtered data to GridView
GridView1.DataBind()

If dsStudents.Tables("Students").Rows.Count = 0 Then
lblMessage.Text = "No students found for the specified
course."
Else
lblMessage.Text = String.Format("{0} student(s) found in
course '{1}'.", dsStudents.Tables("Students").Rows.Count, course)
End If
End Using
End Sub

Private Sub LoadStudentData()


Using connection As New SqlConnection(connectionString)
connection.Open()
Dim selectQuery As String = "SELECT * FROM Student"
Dim selectCommand As New SqlCommand(selectQuery, connection)

Dim adapter As New SqlDataAdapter(selectCommand)


adapter.Fill(dsStudents, "Students") ' Fill a DataTable named
"Students" in the DataSet

GridView1.DataSource = dsStudents.Tables("Students") ' Bind


data to GridView
GridView1.DataBind
45. Write a vb.net application that perform insert, update and delete operations on
Employee table & perform a navigation operation on employee records using
disconnected scenario.

Here's a VB.NET application that performs CRUD (Create, Read, Update, Delete) operations
on an Employee table using a disconnected scenario with a DataSet:

VB.Net
Imports System.Data.SqlClient

Partial Class Default


Inherits System.Web.UI.Page

Dim connectionString As String = "Data


Source=YOUR_SERVER_ADDRESS;Initial Catalog=YOUR_DATABASE_NAME;Integrated
Security=True" ' Replace with your connection string
Dim dsEmployees As New DataSet
Dim currentRow As Integer = 0 ' Track the current row index for
navigation

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles


Me.Load
' Load existing data on page load (optional)
LoadEmployeeData()
If Not IsPostBack Then ' Prevent repopulating on postbacks
currentRow = 0 ' Set initial row index
DisplayEmployeeDetails()
End If
End Sub

Protected Sub btnAddEmployee_Click(sender As Object, e As EventArgs)


Handles btnAddEmployee.Click
Dim empID As Integer = txtEmpID.Text.Trim().ToInt32()
Dim name As String = txtName.Text.Trim()
Dim designation As String = txtDesignation.Text.Trim()
Dim salary As Decimal = Decimal.Parse(txtSalary.Text.Trim())
Dim hireDate As DateTime = Date.Parse(txtHireDate.Text.Trim())

' Add validation checks for empty fields (optional)

Dim newRow As DataRow = dsEmployees.Tables("Employees").NewRow()


newRow["EmpID"] = empID
newRow["Name"] = name
newRow["Designation"] = designation
newRow["Salary"] = salary
newRow["HireDate"] = hireDate
dsEmployees.Tables("Employees").Rows.Add(newRow)

ClearTextBoxes() ' Clear input fields after insertion


currentRow = dsEmployees.Tables("Employees").Rows.Count - 1 ' Set
current row to the last row
DisplayEmployeeDetails()
lblMessage.Text = "Employee record added successfully!"
End Sub

Protected Sub btnUpdateEmployee_Click(sender As Object, e As EventArgs)


Handles btnUpdateEmployee.Click
If currentRow >= 0 AndAlso currentRow <
dsEmployees.Tables("Employees").Rows.Count Then ' Check for valid row
index
Dim empID As Integer =
CInt(dsEmployees.Tables("Employees").Rows(currentRow)("EmpID"))
Dim name As String = txtName.Text.Trim()
Dim designation As String = txtDesignation.Text.Trim()
Dim salary As Decimal = Decimal.Parse(txtSalary.Text.Trim())
Dim hireDate As DateTime = Date.Parse(txtHireDate.Text.Trim())

dsEmployees.Tables("Employees").Rows(currentRow)("Name") = name
dsEmployees.Tables("Employees").Rows(currentRow)("Designation")
= designation
dsEmployees.Tables("Employees").Rows(currentRow)("Salary") =
salary
dsEmployees.Tables("Employees").Rows(currentRow)("HireDate") =
hireDate

UpdateEmployeeData(empID, name, designation, salary, hireDate)


' Update data in database

lblMessage.Text = "Employee record updated successfully!"


Else
lblMessage.Text = "Please select an employee to update."
End If
End Sub

Protected Sub btnDeleteEmployee_Click(sender As Object, e As EventArgs)


Handles btnDeleteEmployee.Click
If currentRow >= 0 AndAlso currentRow <
dsEmployees.Tables("Employees").Rows.Count Then ' Check for valid row
index
Dim empID As Integer =
CInt(dsEmployees.Tables("Employees").Rows(currentRow)("EmpID"))

DeleteEmployeeData(empID) ' Delete data from database

dsEmployees.Tables("Employees").Rows(currentRow).Delete() '
Remove row from DataSet

If currentRow > 0 Then ' Move to previous row after deletion


currentRow -= 1
End If

DisplayEmployeeDetails()
lblMessage.Text = "Employee record deleted successfully!"
Else
lblMessage.Text = "Please select an employee to delete."
End If
End Sub
Protected Sub btnFirst_Click(sender As Object, e As EventArgs) Handles
btnFirst.Click
currentRow = 0
DisplayEmployeeDetails()
End Sub

Protected Sub btnPrevious_Click(sender As Object, e As EventArgs)


Handles btnPrevious.Click
If currentRow > 0 Then
currentRow -= 1
DisplayEmployeeDetails()
End If

You might also like