Program in Details
Program in Details
VB.Net
Module RectangleAreaCalculator
Sub Main()
Dim length As Double
Dim width As Double
Dim area As Double
End Module
Use code with caution.
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.
VB.Net
Module CircleCalculator
Sub Main()
' Declare variables
Dim radius As Double
Dim area As Double
Dim circumference As Double
End Module
Use code with caution.
This program defines a Module named CircleCalculator with a Main sub that executes
when the program runs.
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
End Module
Use code with caution.
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
Console.WriteLine("Calculator closed.")
Console.ReadKey()
End Sub
End Module
Use code with caution.
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())
If areEqual Then
Console.WriteLine("The numbers are equal.")
Else
Console.WriteLine("The numbers are not equal.")
End If
End Module
Use code with caution.
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
End Module
Use code with caution.
This program utilizes a loop and the modulo operator (Mod) for efficient even number
counting:
This is a concise and efficient solution for counting even numbers in a given range.
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)
End Module
Use code with caution.
This program utilizes the Math.Pow function and a loop to generate the pattern:
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
End Module
Use code with caution.
This program combines the concepts of even number checking and console output:
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())
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
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
End Module
Use code with caution.
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.
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
End Module
Use code with caution.
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())
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
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.
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:
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
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.
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.
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
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.
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.
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
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.
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.
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
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.
Here's a simple VB.NET Windows Forms application for generating a restaurant bill:
Form Design:
VB.Net
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
Explanation:
Customization:
You can modify the UI layout and add more controls as needed.
Enhance the code with error handling for invalid input.
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
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.
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
Code Implementation:
VB.Net
Module Module1
Sub Main()
Dim students As New List(Of Student)
' 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
Console.WriteLine("----------------------------------------")
Console.WriteLine("Press any key to close...")
Console.ReadKey()
End Sub
End Module
Use code with caution.
Additional Considerations:
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")).
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
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.
Form Elements:
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.
VB.Net
Private questions As List(Of Question) ' List to store exam questions
Private currentQuestionIndex As Integer = 0 ' Index of the current question
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.
VB.Net
Public Class Form1
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.
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:
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.
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:
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.
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).
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)
Additional Considerations:
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.
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).
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:
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.
' 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
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
Sub Main()
Dim listPrice As Double
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.
VB.Net
Public Class Product
' 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
' 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
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)
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.
VB.Net
Public Class Point
Module Module1
Sub Main()
' Create a Point object
Dim point1 = New Point(3, 5)
point1.Display()
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
Module Module1
Sub Main()
Dim circle1 As New Circle(5)
Console.WriteLine("Circle area: {0:0.00}", circle1.CalculateArea())
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.
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.
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:
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.
C#
public partial class Default : System.Web.UI.Page
{
protected void btnClickMe_Click(object sender, EventArgs e)
{
lblMessage.Text = "Welcome To Radiant";
}
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."
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.
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
}
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.
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
}
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.
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
}
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:
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.
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
}
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.
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
}
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.
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:
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.
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
}
Explanation:
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
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();
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();
}
}
connection.Close();
}
}
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:
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.
C#
using System;
using System.Data;
using System.Data.SqlClient; // Replace with your database provider
namespace
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:
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.
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
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()
deleteCommand.Parameters.AddWithValue("@ID", id)
selectCommand.Parameters.AddWithValue("@Course", course)
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
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
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
dsEmployees.Tables("Employees").Rows(currentRow).Delete() '
Remove row from DataSet
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