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

C# practical file

The document contains a series of programming exercises and solutions in C# covering various concepts such as generating prime numbers, Armstrong numbers, sorting arrays, abstract and sealed classes, jagged arrays, boxing and unboxing, string analysis, exception handling, multiple inheritance using interfaces, delegates for arithmetic operations, and implementing indexers. Each exercise includes a brief description followed by the corresponding C# code and sample output. The exercises are designed to enhance understanding of fundamental programming principles and C# language features.

Uploaded by

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

C# practical file

The document contains a series of programming exercises and solutions in C# covering various concepts such as generating prime numbers, Armstrong numbers, sorting arrays, abstract and sealed classes, jagged arrays, boxing and unboxing, string analysis, exception handling, multiple inheritance using interfaces, delegates for arithmetic operations, and implementing indexers. Each exercise includes a brief description followed by the corresponding C# code and sample output. The exercises are designed to enhance understanding of fundamental programming principles and C# language features.

Uploaded by

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

Index

S.No. Question Page No.

1. Write a C sharp program to generate prime numbers between 1 to200 and


also print to the console.

2. Write a program to print ARMSTRONG number.

3. Write a C sharp program to accept an array of integers (10) and sort them in
ascending order.

4. Write a program to implement the concept of abstract class.

5. Write a program to implement the concept of sealed class.

6. Write a C sharp program for jagged array and display its item through
foreach loop.
7. Write a program to demonstrate boxing and unboxing.

8. Write a program to find number of digit, character, and punctuation in


entered string.
9. Write a program using C# for exception handling.

10. Write a program to implement multiple inheritances using interface.

11. Write a program in C# using a delegate to perform basic arithmetic


operations like addition, subtraction, division, and multiplication.
12. Write a program to implement Indexer.

13. Write a program to implement method overloading.

14. Write a program to implement method overriding.

15. Write a program in C sharp to create a calculator in windows form.

16. Create a front end interface in windows that enables a user to accept the
details of an employee like EmpId ,First Name, Last Name, Gender, Contact
No, Designation, Address and Pin. Create a database that stores all these
details in a table. Also, the front end must have a provision to Add, Update
and Delete a record of an employee.
17. Create a database named MyDb (SQL or MS Access).Connect the database
with your window application to display the data in List boxes using Data
Reader.
18. Display the data from the table in a DataGridView control using dataset.
19. Create a registration form in ASP.NET and use different types of validation
controls.
20. Display the data from the table in a Repeater control using dataset in
ASP.net.
C# Practical

Q1. Write a C sharp program to generate prime numbers between 1 to200 and also print to the
console.

Ans.

using System

class PrimeNumbers
{
static void Main()
{
Console.WriteLine("Prime numbers between 1 and 200 are:\n");

for (int number = 2; number <= 200; number++)


{
if (IsPrime(number))
{
Console.Write(number + " ");
}
}
Console.WriteLine(); // For clean output
}
// Method to check if a number is prime
static bool IsPrime(int num)
{
if (num <= 1)
return false;
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
return false;
}
return true;
}
}

OUTPUT:-

Prime numbers between 1 and 200 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
Q2. Write a program to print ARMSTRONG number.

Ans.

using System;

class ArmstrongNumbers
{
static void Main()
{
Console.WriteLine("Armstrong numbers between 1 and 1000 are:\n");

for (int number = 1; number <= 1000; number++)


{
if (IsArmstrong(number))
{
Console.Write(number + " ");
}
}
Console.WriteLine(); // For clean output
}
// Method to check if a number is an Armstrong number
static bool IsArmstrong(int num)
{
int originalNum = num;
int result = 0;
int digits = num.ToString().Length;
while (num > 0)
{
int digit = num % 10;
result += (int)Math.Pow(digit, digits);
num /= 10;
}
return result == originalNum;
}
}

OUTPUT:-

Armstrong numbers between 1 and 1000 are:

1 2 3 4 5 6 7 8 9 153 370 371 407


Q3. Write a C sharp program to accept an array of integers (10) and sort them in
ascending order.

Ans.

using System;

class SortArray

static void Main()

int[] numbers = new int[10];

Console.WriteLine("Enter 10 integers:");

// Input from user

for (int i = 0; i < numbers.Length; i++)

Console.Write($"Enter number {i + 1}: ");

numbers[i] = Convert.ToInt32(Console.ReadLine());

// Sorting in ascending order

Array.Sort(numbers);

// Display sorted array

Console.WriteLine("\nNumbers in ascending order:");

foreach (int num in numbers)

Console.Write(num + " ");

Console.WriteLine(); // For clean output

OUTPUT:-

Enter 10 integers:

Enter number 1: 45
Enter number 2: 12

Enter number 3: 89

Enter number 4: 7

Enter number 5: 56

Enter number 6: 34

Enter number 7: 23

Enter number 8: 78

Enter number 9: 10

Enter number 10: 5

Numbers in ascending order:

5 7 10 12 23 34 45 56 78 89
Q4. Write a program to implement the concept of abstract class.

Ans.

using System;
// Abstract class
abstract class Shape
{
// Abstract method (no implementation here)
public abstract double Area();

// Non-abstract method
public void Display()
{
Console.WriteLine("Calculating area of the shape:");
}
}
// Derived class 1
class Circle : Shape
{
public double Radius { get; set; }

public Circle(double radius)


{
Radius = radius;
}
// Implement abstract method
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
// Derived class 2
class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
// Implement abstract method
public override double Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
// Create Circle object
Shape circle = new Circle(5);
circle.Display();
Console.WriteLine("Area of Circle: " + circle.Area());
Console.WriteLine();
// Create Rectangle object
Shape rectangle = new Rectangle(4, 6);
rectangle.Display();
Console.WriteLine("Area of Rectangle: " + rectangle.Area());
}
}

OUTPUT:-

Calculating area of the shape:

Area of Circle: 78.53981633974483

Calculating area of the shape:

Area of Rectangle: 24
Q5. Write a program to implement the concept of sealed class.

Ans.

using System;
// Base class
class Vehicle
{
public void ShowType()
{
Console.WriteLine("This is a vehicle.");
}
}
// Sealed class - cannot be inherited
sealed class Car : Vehicle
{
public void ShowModel()
{
Console.WriteLine("This is a car - Model: Honda City.");
}
}
// The following code will cause a compile-time error:
// class SportsCar : Car
// {
// // Error: cannot derive from sealed type 'Car'
// }
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.ShowType(); // Method from base class
myCar.ShowModel(); // Method from sealed class
}
}

OUTPUT:-

This is a vehicle.

This is a car - Model: Honda City.


Q6. Write a C sharp program for jagged array and display its item through foreach loop.

Ans.

using System;

class JaggedArrayExample

static void Main()

// Declare a jagged array with 3 rows

int[][] jaggedArray = new int[3][];

// Initialize each row with different number of elements

jaggedArray[0] = new int[] { 1, 2, 3 };

jaggedArray[1] = new int[] { 4, 5 };

jaggedArray[2] = new int[] { 6, 7, 8, 9 };

Console.WriteLine("Elements of the jagged array:\n");

// Loop through each array in the jagged array

int row = 0;

foreach (int[] innerArray in jaggedArray)

Console.Write($"Row {row}: ");

foreach (int item in innerArray)

Console.Write(item + " ");

Console.WriteLine();

row++;

}}}
OUTPUT:-

Elements of the jagged array:

Row 0: 1 2 3
Row 1: 4 5
Row 2: 6 7 8 9
Q7. Write a program to demonstrate boxing and unboxing.

Ans.

using System;

class BoxingUnboxingDemo
{
static void Main()
{
int num = 100; // Value type
object obj = num; // Boxing: Converting value type to object type
Console.WriteLine("Boxing:");
Console.WriteLine("Value type 'int' num = " + num);
Console.WriteLine("Boxed into object obj = " + obj);
int unboxedNum = (int)obj; // Unboxing: Converting object back to value type
Console.WriteLine("\nUnboxing:");
Console.WriteLine("Unboxed object obj back to int = " + unboxedNum);
}
}

OUTPUT:-

Boxing:
Value type 'int' num = 100
Boxed into object obj = 100

Unboxing:
Unboxed object obj back to int = 100
Q8. Write a program to find number of digit, character, and punctuation in entered string.

Ans.

using System;

class StringAnalysis

static void Main()

Console.Write("Enter a string: ");

string input = Console.ReadLine();

int digitCount = 0;

int letterCount = 0;

int punctuationCount = 0;

foreach (char ch in input)

if (char.IsDigit(ch))

digitCount++;

else if (char.IsLetter(ch))

letterCount++;

else if (char.IsPunctuation(ch))

punctuationCount++;

Console.WriteLine("\nAnalysis of the entered string:");


Console.WriteLine("Number of digits: " + digitCount);

Console.WriteLine("Number of letters: " + letterCount);

Console.WriteLine("Number of punctuation marks: " + punctuationCount);

OUTPUT:-

Enter a string: Hello123! How are you doing today? I'm fine :)

Analysis of the entered string:

Number of digits: 3

Number of letters: 31

Number of punctuation marks: 4


Q9. Write a program using C# for exception handling.

Ans.

using System;

class ExceptionHandlingDemo

static void Main()

try

Console.Write("Enter a number: ");

int num1 = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter another number: ");

int num2 = Convert.ToInt32(Console.ReadLine());

int result = num1 / num2; // Division operation which may cause exception (divide by zero)

Console.WriteLine("Result of division: " + result);

catch (DivideByZeroException ex)

Console.WriteLine("Error: Cannot divide by zero.");

catch (FormatException ex)

Console.WriteLine("Error: Please enter a valid integer.");

catch (Exception ex)

Console.WriteLine("An unexpected error occurred: " + ex.Message);

}
finally

Console.WriteLine("Execution completed.");

OUTPUT 1:-

Enter a number: 10

Enter another number: 2

Result of division: 5

Execution completed.

OUTPUT 2:-

Enter a number: 10

Enter another number: 0

Error: Cannot divide by zero.

Execution completed.

OUTPUT 3:-

Enter a number: ten

Error: Please enter a valid integer.

Execution completed.
Q10. Write a program to implement multiple inheritances using interface.

Ans.

using System;

// Interface 1

interface IShape

void Draw();

// Interface 2

interface IColor

void FillColor();

// Class implementing both interfaces (Multiple Inheritance)

class Circle : IShape, IColor

public void Draw()

Console.WriteLine("Drawing the circle...");

public void FillColor()

Console.WriteLine("Filling the circle with color...");

class Program
{

static void Main()

// Create an object of Circle

Circle circle = new Circle();

// Calling methods from both interfaces

circle.Draw();

circle.FillColor();

OUTPUT:-

Drawing the circle...

Filling the circle with color...


Q11. Write a program in C# using a delegate to perform basic arithmetic operations like
addition, subtraction, division, and multiplication.

Ans.

using System;

// Define a delegate that takes two integers and returns an integer

delegate int ArithmeticOperation(int num1, int num2);

class ArithmeticOperations

// Method for Addition

public static int Add(int num1, int num2)

return num1 + num2;

// Method for Subtraction

public static int Subtract(int num1, int num2)

return num1 - num2;

// Method for Multiplication

public static int Multiply(int num1, int num2)

return num1 * num2;

// Method for Division

public static int Divide(int num1, int num2)

if (num2 == 0)

Console.WriteLine("Error: Division by zero.");

return 0;

}
return num1 / num2;

static void Main()

// Input from user

Console.Write("Enter first number: ");

int num1 = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter second number: ");

int num2 = Convert.ToInt32(Console.ReadLine());

// Create delegate instances for each operation

ArithmeticOperation add = new ArithmeticOperation(Add);

ArithmeticOperation subtract = new ArithmeticOperation(Subtract);

ArithmeticOperation multiply = new ArithmeticOperation(Multiply);

ArithmeticOperation divide = new ArithmeticOperation(Divide);

// Perform and display each operation

Console.WriteLine("\nArithmetic Operations:");

Console.WriteLine($"Addition: {add(num1, num2)}");

Console.WriteLine($"Subtraction: {subtract(num1, num2)}");

Console.WriteLine($"Multiplication: {multiply(num1, num2)}");

Console.WriteLine($"Division: {divide(num1, num2)}");

OUTPUT:-

Enter first number: 10

Enter second number: 5

Arithmetic Operations:

Addition: 15

Subtraction: 5

Multiplication: 50

Division: 2
Q12. Write a program to implement Indexer.

Ans.

using System;

class Student

private string[] names;

// Constructor to initialize the names array

public Student(int size)

names = new string[size];

// Indexer to access the names array like an array

public string this[int index]

get

// Check if the index is valid

if (index >= 0 && index < names.Length)

return names[index];

else

return "Invalid index";

set

// Check if the index is valid

if (index >= 0 && index < names.Length)

{
names[index] = value;

else

Console.WriteLine("Invalid index");

class Program

static void Main()

// Create an object of the Student class with 3 student names

Student studentList = new Student(3);

// Assign values to the array elements using the indexer

studentList[0] = "John";

studentList[1] = "Alice";

studentList[2] = "Bob";

// Access the values using the indexer

Console.WriteLine("Student at index 0: " + studentList[0]);

Console.WriteLine("Student at index 1: " + studentList[1]);

Console.WriteLine("Student at index 2: " + studentList[2]);

// Accessing an invalid index

Console.WriteLine("Student at index 5: " + studentList[5]);

}
OUTPUT:-

Student at index 0: John

Student at index 1: Alice

Student at index 2: Bob

Student at index 5: Invalid index


Q13. Write a program to implement method overloading.

Ans.

using System;

class Calculator

// Method to add two integers

public int Add(int num1, int num2)

return num1 + num2;

// Overloaded method to add three integers

public int Add(int num1, int num2, int num3)

return num1 + num2 + num3;

// Overloaded method to add two floating-point numbers

public double Add(double num1, double num2)

return num1 + num2;

// Overloaded method to add two strings as numbers

public double Add(string num1, string num2)

double n1 = Convert.ToDouble(num1);

double n2 = Convert.ToDouble(num2);

return n1 + n2;

}
}

class Program

static void Main()

Calculator calculator = new Calculator();

// Calling different overloaded methods

Console.WriteLine("Sum of two integers (5 + 10): " + calculator.Add(5, 10));

Console.WriteLine("Sum of three integers (5 + 10 + 15): " + calculator.Add(5, 10, 15));

Console.WriteLine("Sum of two doubles (5.5 + 10.5): " + calculator.Add(5.5, 10.5));

Console.WriteLine("Sum of two strings ('5.5' + '10.5'): " + calculator.Add("5.5", "10.5"));

OUTPUT:-

Sum of two integers (5 + 10): 15

Sum of three integers (5 + 10 + 15): 30

Sum of two doubles (5.5 + 10.5): 16

Sum of two strings ('5.5' + '10.5'): 16


Q14. Write a program to implement method overriding.

Ans.

using System;

// Base class

class Animal

// Virtual method in the base class

public virtual void Sound()

Console.WriteLine("Animal makes a sound");

// Derived class

class Dog : Animal

// Overriding the Sound method in the derived class

public override void Sound()

Console.WriteLine("Dog barks");

// Another derived class

class Cat : Animal

// Overriding the Sound method in the derived class

public override void Sound()

Console.WriteLine("Cat meows");
}

class Program

static void Main()

// Creating objects of derived classes

Animal myDog = new Dog();

Animal myCat = new Cat();

// Calling the overridden methods

myDog.Sound(); // Dog-specific sound

myCat.Sound(); // Cat-specific sound

OUTPUT:-

Dog barks

Cat meows
Q15. Write a program in C sharp to create a calculator in windows form.

Ans.

using System;

using System.Windows.Forms;

namespace WindowsFormsCalculator

public partial class CalculatorForm : Form

private double resultValue = 0;

private string operatorUsed = "";

private bool isOperatorClicked = false;

public CalculatorForm()

InitializeComponent();

// When the number button is clicked

private void NumberButton_Click(object sender, EventArgs e)

if ((textBox_Display.Text == "0") || isOperatorClicked)

textBox_Display.Clear();

isOperatorClicked = false;

Button button = (Button)sender;

textBox_Display.Text += button.Text;

// When the operator button is clicked (+, -, *, /)


private void OperatorButton_Click(object sender, EventArgs e)

Button button = (Button)sender;

operatorUsed = button.Text;

resultValue = double.Parse(textBox_Display.Text);

isOperatorClicked = true;

// When the '=' button is clicked

private void EqualsButton_Click(object sender, EventArgs e)

switch (operatorUsed)

case "+":

textBox_Display.Text = (resultValue + double.Parse(textBox_Display.Text)).ToString();

break;

case "-":

textBox_Display.Text = (resultValue - double.Parse(textBox_Display.Text)).ToString();

break;

case "*":

textBox_Display.Text = (resultValue * double.Parse(textBox_Display.Text)).ToString();

break;

case "/":

if (double.Parse(textBox_Display.Text) == 0)

textBox_Display.Text = "Error";

else

textBox_Display.Text = (resultValue / double.Parse(textBox_Display.Text)).ToString();

}
break;

default:

break;

// When the 'C' button (Clear) is clicked

private void ClearButton_Click(object sender, EventArgs e)

textBox_Display.Clear();

resultValue = 0;

operatorUsed = "";

Form Design (Windows Forms Designer):-


namespace WindowsFormsCalculator

partial class CalculatorForm

private System.ComponentModel.IContainer components = null;

private System.Windows.Forms.TextBox textBox_Display;

private System.Windows.Forms.Button button_1;

private System.Windows.Forms.Button button_2;

private System.Windows.Forms.Button button_3;

private System.Windows.Forms.Button button_4;

private System.Windows.Forms.Button button_5;

private System.Windows.Forms.Button button_6;

private System.Windows.Forms.Button button_7;


private System.Windows.Forms.Button button_8;

private System.Windows.Forms.Button button_9;

private System.Windows.Forms.Button button_0;

private System.Windows.Forms.Button button_Add;

private System.Windows.Forms.Button button_Subtract;

private System.Windows.Forms.Button button_Multiply;

private System.Windows.Forms.Button button_Divide;

private System.Windows.Forms.Button button_Equals;

private System.Windows.Forms.Button button_Clear;

private void InitializeComponent()

this.textBox_Display = new System.Windows.Forms.TextBox();

this.button_1 = new System.Windows.Forms.Button();

this.button_2 = new System.Windows.Forms.Button();

this.button_3 = new System.Windows.Forms.Button();

this.button_4 = new System.Windows.Forms.Button();

this.button_5 = new System.Windows.Forms.Button();

this.button_6 = new System.Windows.Forms.Button();

this.button_7 = new System.Windows.Forms.Button();

this.button_8 = new System.Windows.Forms.Button();

this.button_9 = new System.Windows.Forms.Button();

this.button_0 = new System.Windows.Forms.Button();

this.button_Add = new System.Windows.Forms.Button();

this.button_Subtract = new System.Windows.Forms.Button();

this.button_Multiply = new System.Windows.Forms.Button();

this.button_Divide = new System.Windows.Forms.Button();

this.button_Equals = new System.Windows.Forms.Button();

this.button_Clear = new System.Windows.Forms.Button();

this.SuspendLayout();
//

// textBox_Display

//

this.textBox_Display.Location = new System.Drawing.Point(12, 12);

this.textBox_Display.Name = "textBox_Display";

this.textBox_Display.Size = new System.Drawing.Size(260, 20);

this.textBox_Display.TabIndex = 0;

this.textBox_Display.Text = "0";

this.textBox_Display.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

//

// Number Buttons (0-9)

//

this.button_1.Location = new System.Drawing.Point(12, 50);

this.button_1.Size = new System.Drawing.Size(50, 50);

this.button_1.Text = "1";

this.button_1.Click += new System.EventHandler(this.NumberButton_Click);

this.button_2.Location = new System.Drawing.Point(68, 50);

this.button_2.Size = new System.Drawing.Size(50, 50);

this.button_2.Text = "2";

this.button_2.Click += new System.EventHandler(this.NumberButton_Click);

// Repeat for other number buttons (3, 4, 5, 6, 7, 8, 9, 0)

//

// Operator Buttons (+, -, *, /)

//

this.button_Add.Location = new System.Drawing.Point(174, 50);

this.button_Add.Size = new System.Drawing.Size(50, 50);


this.button_Add.Text = "+";

this.button_Add.Click += new System.EventHandler(this.OperatorButton_Click);

this.button_Subtract.Location = new System.Drawing.Point(174, 106);

this.button_Subtract.Size = new System.Drawing.Size(50, 50);

this.button_Subtract.Text = "-";

this.button_Subtract.Click += new System.EventHandler(this.OperatorButton_Click);

// Repeat for other operators (*, /)

//

// Equals Button (=)

//

this.button_Equals.Location = new System.Drawing.Point(174, 212);

this.button_Equals.Size = new System.Drawing.Size(50, 50);

this.button_Equals.Text = "=";

this.button_Equals.Click += new System.EventHandler(this.EqualsButton_Click);

//

// Clear Button (C)

//

this.button_Clear.Location = new System.Drawing.Point(68, 212);

this.button_Clear.Size = new System.Drawing.Size(50, 50);

this.button_Clear.Text = "C";

this.button_Clear.Click += new System.EventHandler(this.ClearButton_Click);

//

// CalculatorForm

//

this.ClientSize = new System.Drawing.Size(284, 261);

this.Controls.Add(this.textBox_Display);
this.Controls.Add(this.button_1);

this.Controls.Add(this.button_2);

this.Controls.Add(this.button_3);

this.Controls.Add(this.button_4);

this.Controls.Add(this.button_5);

this.Controls.Add(this.button_6);

this.Controls.Add(this.button_7);

this.Controls.Add(this.button_8);

this.Controls.Add(this.button_9);

this.Controls.Add(this.button_0);

this.Controls.Add(this.button_Add);

this.Controls.Add(this.button_Subtract);

this.Controls.Add(this.button_Multiply);

this.Controls.Add(this.button_Divide);

this.Controls.Add(this.button_Equals);

this.Controls.Add(this.button_Clear);

this.Name = "CalculatorForm";

this.Text = "Calculator";

this.ResumeLayout(false);

this.PerformLayout();

OUTPUT:-

When you run the application, you will see a simple calculator UI with buttons for digits,
operators, and result.
Q16. Create a front end interface in windows that enables a user to accept the details of an
employee like EmpId ,First Name, Last Name, Gender, Contact No, Designation, Address and
Pin. Create a database that stores all these details in a table. Also, the front end must have a
provision to Add, Update and Delete a record of an employee.

Ans.

Database Setup (SQL Server):-


CREATE DATABASE EmployeeDB;

USE EmployeeDB;

CREATE TABLE Employees (

EmpId INT PRIMARY KEY,

FirstName NVARCHAR(50),

LastName NVARCHAR(50),

Gender NVARCHAR(10),

ContactNo NVARCHAR(15),

Designation NVARCHAR(50),

Address NVARCHAR(100),

Pin NVARCHAR(10)

);

Code for Form1.cs:-


using System;

using System.Data;

using System.Data.SqlClient;

using System.Windows.Forms;

namespace EmployeeFormApp

{
public partial class Form1 : Form

string connectionString = "Data Source=YOUR_SERVER_NAME;Initial


Catalog=EmployeeDB;Integrated Security=True";

public Form1()

InitializeComponent();

LoadData();

private void LoadData()

using (SqlConnection con = new SqlConnection(connectionString))

SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Employees", con);

DataTable dt = new DataTable();

sda.Fill(dt);

dataGridView1.DataSource = dt;

private void btnAdd_Click(object sender, EventArgs e)

using (SqlConnection con = new SqlConnection(connectionString))

string query = "INSERT INTO Employees VALUES (@EmpId, @FirstName, @LastName,


@Gender, @ContactNo, @Designation, @Address, @Pin)";

SqlCommand cmd = new SqlCommand(query, con);

cmd.Parameters.AddWithValue("@EmpId", txtEmpId.Text);

cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);

cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Gender", cmbGender.Text);

cmd.Parameters.AddWithValue("@ContactNo", txtContact.Text);

cmd.Parameters.AddWithValue("@Designation", txtDesignation.Text);

cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

cmd.Parameters.AddWithValue("@Pin", txtPin.Text);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("Record Added Successfully!");

LoadData();

ClearFields();

private void btnUpdate_Click(object sender, EventArgs e)

using (SqlConnection con = new SqlConnection(connectionString))

string query = @"UPDATE Employees SET

FirstName = @FirstName,

LastName = @LastName,

Gender = @Gender,

ContactNo = @ContactNo,

Designation = @Designation,

Address = @Address,

Pin = @Pin

WHERE EmpId = @EmpId";

SqlCommand cmd = new SqlCommand(query, con);

cmd.Parameters.AddWithValue("@EmpId", txtEmpId.Text);

cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);

cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Gender", cmbGender.Text);

cmd.Parameters.AddWithValue("@ContactNo", txtContact.Text);

cmd.Parameters.AddWithValue("@Designation", txtDesignation.Text);

cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

cmd.Parameters.AddWithValue("@Pin", txtPin.Text);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("Record Updated Successfully!");

LoadData();

ClearFields();

private void btnDelete_Click(object sender, EventArgs e)

using (SqlConnection con = new SqlConnection(connectionString))

string query = "DELETE FROM Employees WHERE EmpId = @EmpId";

SqlCommand cmd = new SqlCommand(query, con);

cmd.Parameters.AddWithValue("@EmpId", txtEmpId.Text);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("Record Deleted Successfully!");

LoadData();

ClearFields();

private void ClearFields()

{
txtEmpId.Clear();

txtFirstName.Clear();

txtLastName.Clear();

txtContact.Clear();

txtDesignation.Clear();

txtAddress.Clear();

txtPin.Clear();

cmbGender.SelectedIndex = -1;

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

if (e.RowIndex >= 0)

DataGridViewRow row = dataGridView1.Rows[e.RowIndex];

txtEmpId.Text = row.Cells[0].Value.ToString();

txtFirstName.Text = row.Cells[1].Value.ToString();

txtLastName.Text = row.Cells[2].Value.ToString();

cmbGender.Text = row.Cells[3].Value.ToString();

txtContact.Text = row.Cells[4].Value.ToString();

txtDesignation.Text = row.Cells[5].Value.ToString();

txtAddress.Text = row.Cells[6].Value.ToString();

txtPin.Text = row.Cells[7].Value.ToString();

OUTPUT:-

The form shows fields to input employee data.

You can Add, Edit, or Delete entries.

All changes reflect instantly in the DataGridView.


Q17. Create a database named MyDb (SQL or MS Access).Connect the database with your
window application to display the data in List boxes using Data Reader.

Ans.

Step 1: Create the SQL Server Database:-


CREATE DATABASE MyDb;

USE MyDb;

CREATE TABLE Employees (

EmpId INT PRIMARY KEY,

FirstName NVARCHAR(50),

Designation NVARCHAR(50)

);

-- Sample data

INSERT INTO Employees VALUES (1, 'Love', 'Developer');

INSERT INTO Employees VALUES (2, 'Verma', 'Designer');

INSERT INTO Employees VALUES (3, 'Ankit', 'Tester');

Step 2: Design Windows Form UI:-


Use the Visual Studio designer to add:

• ListBox1 → for EmpId

• ListBox2 → for FirstName

• ListBox3 → for Designation

• Button → named btnLoad with text "Load Data"

Step 3: C# Code for Form:-


using System;

using System.Data.SqlClient;

using System.Windows.Forms;
namespace MyDbReaderApp

public partial class Form1 : Form

string connectionString = "Data Source=YOUR_SERVER_NAME;Initial


Catalog=MyDb;Integrated Security=True";

public Form1()

InitializeComponent();

private void btnLoad_Click(object sender, EventArgs e)

listBox1.Items.Clear();

listBox2.Items.Clear();

listBox3.Items.Clear();

using (SqlConnection con = new SqlConnection(connectionString))

string query = "SELECT EmpId, FirstName, Designation FROM Employees";

SqlCommand cmd = new SqlCommand(query, con);

con.Open();

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

listBox1.Items.Add(reader["EmpId"].ToString());

listBox2.Items.Add(reader["FirstName"].ToString());
listBox3.Items.Add(reader["Designation"].ToString());

reader.Close();

con.Close();

OUTPUT:-

ListBox1 (EmpId):-
1

ListBox2 (FirstName):-
Kush

Love

Ankit

ListBox3 (Designation):-
Developer

Designer

Tester
Q18. Display the data from the table in a DataGridView control using dataset.

Ans.

Step 1: SQL Server Setup:-


-- Create database and table

CREATE DATABASE MyDb;

USE MyDb;

CREATE TABLE Employees (

EmpId INT PRIMARY KEY,

FirstName NVARCHAR(50),

LastName NVARCHAR(50),

Designation NVARCHAR(50)

);

-- Insert sample data

INSERT INTO Employees VALUES (1, 'Love', 'Verma', 'Developer');

INSERT INTO Employees VALUES (2, 'Ankit', 'Sharma', 'Tester');

INSERT INTO Employees VALUES (3, 'Riya', 'Singh', 'Designer');

Step 2: Form Design in Visual Studio:-


• Create a Windows Forms App (.NET Framework)

• Add a DataGridView (dataGridView1)

• Add a Button (btnLoad) with text: Load Data

Step 3: Add Namespaces:-


using System;

using System.Data;

using System.Data.SqlClient;

using System.Windows.Forms;
Step 4: Full Code for Form1.cs:-
namespace MyDbGridViewApp

public partial class Form1 : Form

// Update YOUR_SERVER_NAME with actual SQL Server name

string connectionString = "Data Source=YOUR_SERVER_NAME;Initial


Catalog=MyDb;Integrated Security=True";

public Form1()

InitializeComponent();

private void btnLoad_Click(object sender, EventArgs e)

using (SqlConnection con = new SqlConnection(connectionString))

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", con);

DataSet ds = new DataSet();

adapter.Fill(ds, "Employees");

dataGridView1.DataSource = ds.Tables["Employees"];

}
Output (after clicking Load Data):-
EmpId FirstName LastName Designation

1 Love Verma Developer

2 Ankit Sharma Tester

3 Riya Singh Designer


Q19. Create a registration form in ASP.NET and use different types of validation controls.

Ans.

Step 1: ASPX Page (RegistrationForm.aspx):-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RegistrationForm.aspx.cs"
Inherits="RegistrationForm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Registration Form with Validation</title>

<style>

.form-group { margin: 10px 0; }

.form-control { width: 250px; }

.error { color: red; font-size: small; }

</style>

</head>

<body>

<form id="form1" runat="server">

<div style="margin: 50px;">

<h2>Registration Form</h2>

<div class="form-group">

<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label><br />

<asp:TextBox ID="txtName" runat="server" CssClass="form-control"></asp:TextBox>

<asp:RequiredFieldValidator ID="rfvName" runat="server"

ControlToValidate="txtName"

ErrorMessage="Name is required" CssClass="error" Display="Dynamic" />

</div>

<div class="form-group">

<asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label><br />


<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>

<asp:RequiredFieldValidator ID="rfvEmail" runat="server"

ControlToValidate="txtEmail"

ErrorMessage="Email is required" CssClass="error" Display="Dynamic" />

<asp:RegularExpressionValidator ID="revEmail" runat="server"

ControlToValidate="txtEmail"

ValidationExpression="^[^@\s]+@[^@\s]+\.[^@\s]+$"

ErrorMessage="Invalid email format" CssClass="error" Display="Dynamic" />

</div>

<div class="form-group">

<asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label><br />

<asp:TextBox ID="txtPassword" runat="server" CssClass="form-control"


TextMode="Password"></asp:TextBox>

<asp:RequiredFieldValidator ID="rfvPassword" runat="server"

ControlToValidate="txtPassword"

ErrorMessage="Password is required" CssClass="error" Display="Dynamic" />

</div>

<div class="form-group">

<asp:Label ID="lblConfirmPassword" runat="server" Text="Confirm


Password:"></asp:Label><br />

<asp:TextBox ID="txtConfirmPassword" runat="server" CssClass="form-control"


TextMode="Password"></asp:TextBox>

<asp:CompareValidator ID="cvPassword" runat="server"

ControlToCompare="txtPassword"

ControlToValidate="txtConfirmPassword"

ErrorMessage="Passwords do not match" CssClass="error" Display="Dynamic" />

</div>

<div class="form-group">

<asp:Label ID="lblAge" runat="server" Text="Age:"></asp:Label><br />


<asp:TextBox ID="txtAge" runat="server" CssClass="form-control"></asp:TextBox>

<asp:RangeValidator ID="rvAge" runat="server"

ControlToValidate="txtAge"

MinimumValue="18"

MaximumValue="60"

Type="Integer"

ErrorMessage="Age must be between 18 and 60" CssClass="error" Display="Dynamic"


/>

</div>

<div class="form-group">

<asp:Button ID="btnRegister" runat="server" Text="Register"


OnClick="btnRegister_Click" />

</div>

<asp:Label ID="lblMessage" runat="server" ForeColor="Green" Font-


Bold="true"></asp:Label>

</div>

</form>

</body>

</html>

Step 2: Code-Behind (RegistrationForm.aspx.cs):-


using System;

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

protected void Page_Load(object sender, EventArgs e)

}
protected void btnRegister_Click(object sender, EventArgs e)

if (Page.IsValid)

lblMessage.Text = "Registration successful!";

OUTPUT:-

Registration successful!
Q20. Display the data from the table in a Repeater control using dataset in ASP.net.

Ans.

Step 1: Create SQL Table and Insert Sample Data:-


CREATE DATABASE MyDb;

USE MyDb;

CREATE TABLE Students (

StudentId INT PRIMARY KEY,

Name NVARCHAR(50),

Course NVARCHAR(50)

);

INSERT INTO Students VALUES

(1, 'Love Verma', 'MCA'),

(2, 'Ankit Sharma', 'B.Tech'),

(3, 'Riya Singh', 'BCA');

Step 2: ASPX Page (RepeaterDemo.aspx):-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterDemo.aspx.cs"
Inherits="RepeaterDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Repeater Example with DataSet</title>

<style>

.student-box {

border: 1px solid #ccc;

padding: 10px;

margin: 8px;

background-color: #f5f5f5;
width: 300px;

</style>

</head>

<body>

<form id="form1" runat="server">

<h2>Students List</h2>

<asp:Repeater ID="Repeater1" runat="server">

<ItemTemplate>

<div class="student-box">

<strong>ID:</strong> <%# Eval("StudentId") %><br />

<strong>Name:</strong> <%# Eval("Name") %><br />

<strong>Course:</strong> <%# Eval("Course") %>

</div>

</ItemTemplate>

</asp:Repeater>

</form>

</body>

</html>

Step 3: Code-Behind (RepeaterDemo.aspx.cs):-


using System;

using System.Data;

using System.Data.SqlClient;

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

string connectionString = "Data Source=YOUR_SERVER_NAME;Initial


Catalog=MyDb;Integrated Security=True";

protected void Page_Load(object sender, EventArgs e)


{

if (!IsPostBack)

BindRepeater();

private void BindRepeater()

using (SqlConnection con = new SqlConnection(connectionString))

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Students", con);

DataSet ds = new DataSet();

adapter.Fill(ds, "Students");

Repeater1.DataSource = ds.Tables["Students"];

Repeater1.DataBind();

OUTPUT:-

Students List

[Student 1 Box]

ID: 1

Name: Love Verma

Course: MCA

[Student 2 Box]

ID: 2

Name: Ankit Sharma


Course: B.Tech

[Student 3 Box]

ID: 3

Name: Riya Singh

Course: BCA

You might also like