You are on page 1of 53

1.

Write a C sharp program to generate prime numbers between 1 to


200 and also print to the console. (ex. 1,2,3,5.....................199).

using System;

namespace primemethod
{
class primenumber
{
public static void Main()
{
bool notPrime = false;
int j;
int target = 200;

for (int i = 2; i <= target; i++)


{
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
notPrime = true;
break;
}
}

if (!notPrime)
Console.Write("{0} ", j);
else
notPrime = false;
}

Console.ReadLine();
}

}
}

1
Output:

2
2. Write a program to print ARMSTRONG number.

using System;

class Armstrongnumber
{
public static void Main()
{
int i, num, count = 0;
double sum;

for (i = 1; i <= 1000; i++)


{
num = i;

while (num != 0)
{
num /= 10;
count++;
}
num = i;
sum = Math.Pow(num % 10, count)
+ Math.Pow((num % 100 - num % 10) / 10, count)
+ Math.Pow((num % 1000 - num % 100) / 100, count);
// Check for Armstrong Number
if (sum == i)
{
Console.WriteLine(i);
}
count = 0;
}
Console.ReadLine();

3
Output:

4
3. Write a C sharp program using loop that examines all the numbers
between 2 and 1000, and displays only Perfect numbers. (A perfect
number is the one whose sum of their divisors equals the number
itself).For example given the number 6, the sum of its divisors is
6(1+2+3).Hence, 6 is a perfect number.

using System;

namespace perfectnumber
{
internal class perfectnumber
{
static void Main(string[] args)
{
int i, j;
int sum = 0;
for ( i = 2;i<1000;i++)
{

int m = i;

for ( j = 1; j <i; j++)


{
if (i%j == 0)
{
sum = sum + j;
}

}
if (sum == m)
Console.WriteLine(sum);
sum = 0;

}
Console.ReadLine();

}
}
}

5
Output:

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

using System;

internal class Program


{
public static void Main(string[] args)
{

int[] arr = { 5, 8, 9, 7, 6, 2, 3, 1, 4 };
Console.WriteLine("list of array before sort ");
foreach (int item in arr)
{

Console.Write(" "+ item);


}
Array.Sort(arr);
Console.WriteLine("\narray after sorting:");
foreach(int item in arr)
{
Console.Write(" "+ item);
}

Console.ReadLine();

7
Output:

8
5. Write a program to implement the concept of abstract class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace abstract_class
{
abstract class Motorbike
{
public abstract void Motorbreak();

}
class sportsbike : Motorbike
{
public override void Motorbreak()
{
Console.WriteLine("sportbike break applied:");
}
}
class mountainbike : Motorbike
{

public override void Motorbreak()


{
Console.WriteLine("mountaibike break applied:");
}
}
class program
{
public static void Main(string[] args)
{
sportsbike s1 = new sportsbike();
s1.Motorbreak();
mountainbike m1 = new mountainbike();
m1.Motorbreak();

Console.ReadLine();
}
}
}

9
Output:

10
6.Write a program to implement the concept of sealed class.

using System;

namespace Sealed_class
{
sealed class animal
{
public virtual void sound()
{
Console.WriteLine("Animal Sound:");
}
}
class Dog:animal
{
public override void sound()
{
Console.WriteLine("dog sound");
}
}
internal class Program
{
static void Main(string[] args)
{
Dog d1 = new Dog();
d1.sound();
Console.ReadLine();
}
}
}

11
Output:

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jaggedarray
{
internal class Program
{
static void Main(string[] args)
{
int[][] arr = new int[4][];
arr[0] =new int [5] {1,2,3,4,5};
arr[1] =new int [4]{6,7,8,9};
arr[2]= new int [4]{10,11,12,13 };
arr[3] =new int [3]{14, 15, 16,};

Console.WriteLine("element of jagged array:");


foreach(int[] i in arr)
{
foreach (int j in i)
{
Console.Write(j);
}
Console.WriteLine();

}
Console.ReadLine();

}
}
}

13
Output:

14
8. Write a program in C Sharp using a class that gets the information
about employee's such as Emp Id, First Name, Last Name, Basic Salary,
Grade, Address, Pin Code and Contact Number. Write a method that
calculates the Gross Salary (Basic +DA+HRA) and return to the calling
program and another method for the Net salary (Gross - (P.F + Income
Tax)).Finally write a method that prints, a pay slip of an employee,
containg all the above components in a proper format to the console.
(Grade A = 20,000 , B=15,000 and C=10,000) DA=56% and HRA=20%.,
Pf=780, ITax.

using System;

class Employee
{
public int EmpId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public double BasicSalary { get; set; }
public char Grade { get; set; }
public string Address { get; set; }
public string PinCode { get; set; }
public string ContactNumber { get; set; }

// Constants for grade-specific salaries


const double GradeASalary = 20000;
const double GradeBSalary = 15000;
const double GradeCSalary = 10000;

// Constants for other components


const double DA = 0.56; // 56% of Basic Salary
const double HRA = 0.20; // 20% of Basic Salary
const double PF = 780;
const double IncomeTax = 0.10; // 10% of Gross Salary

// Calculate Gross Salary


public double CalculateGrossSalary()
{
double grossSalary = BasicSalary + (BasicSalary * DA) + (BasicSalary * HRA);
return grossSalary;
}

// Calculate Net Salary


public double CalculateNetSalary()
{
double grossSalary = CalculateGrossSalary();
double netSalary = grossSalary - (PF + (grossSalary * IncomeTax));
return netSalary;
}

// Print Pay Slip


public void PrintPaySlip()
{
double grossSalary = CalculateGrossSalary();

15
Console.WriteLine("Address: " + Address);
Console.WriteLine("Pin Code: " + PinCode);
Console.WriteLine("Contact Number: " + ContactNumber);
Console.WriteLine("Gross Salary: " + grossSalary);
Console.WriteLine("Net Salary: " + netSalary);
}
}

class Program
{
static void Main()
{
Employee employee = new Employee
{
EmpId = 1,
FirstName = "John",
LastName = "Doe",
BasicSalary = 15000,
Grade = 'B',
Address = "123 Main St",
PinCode = "12345",
ContactNumber = "123-456-7890"
};

employee.PrintPaySlip();
}
}

16
Output:

17
9. Write a program to demonstrate boxing and unboxing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;

namespace boxingandunboxing
{
internal class Program
{
static void Main(string[] args)
{
//Boxing demonstrate.....
Console.WriteLine("Under Boxing Demonstrate:");
int num = 1000;
object obj = num;
num = 100;
Console.WriteLine("The Value of object is"+obj);
Console.WriteLine("The Value of num is:" + num);

Console.WriteLine();
//Unboxing Demonstrate......
Console.WriteLine("Under UnBoxing Demonstrate:");
int ded = 1001;
object ob = ded;
int i = (int)ob;
Console.WriteLine("The Value of object is :" + ob);
Console.WriteLine("The Value i is :" + i);
Console.ReadLine();
}

}
}

18
Output:

19
10. Write a program to find number of digits, character, and
punctuation in entered string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace stringProg
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a String:");
String txt = Console.ReadLine();
int count_dig = 0;
int count_punctuation = 0;
int count_char = 0;
for (int i = 0; i < txt.Length; i++)
{
count_char += 1;
if (txt[i] == '0' || txt[i] == '1' || txt[i] == '2' || txt[i] == '3' || txt[i] == '4' ||
txt[i] == '5' || txt[i] == '5' || txt[i] == '6' || txt[i] == '7' || txt[i] == '8' ||
txt[i] == '9' || txt[i] == '0')
{
count_dig += 1;
}
else if (txt[i] == '.' || txt[i] == '?' || txt[i] == '!' || txt[i] == '"' || txt[i] == '/' || txt[i] == ':'
|| txt[i] == ';' || txt[i] == '_' || txt[i] == '-')
{
count_punctuation += 1;
}

}
Console.WriteLine($"character in String = {count_char},\n digits in string:{count_dig},\n Punctuation in String:
{count_punctuation}");
Console.ReadLine();
}

20
Output:

21
11. Write a program using C# for exception handling.

using System;

namespace exception_handling
{
internal class divnumber
{
int result;
divnumber()
{
result = 0;
}
public void division(int num1,int num2) {
try
{
result = num1 / num2;

}
catch (DivideByZeroException e) {
Console.WriteLine("exception Caught:{0}" ,e);
}
finally
{
Console.WriteLine("Result : {0}", result);
}

}
static void Main(string[] args)
{
divnumber d = new divnumber();
d.division(20,0);
Console.ReadKey();

}
}
}

22
Output:

23
12. Write a program to implement multiple inheritances using interface.

using System;

namespace Multipleinheritence
{
interface calc_add
{
int add(int a, int b);
}
interface calc_sub
{
int sub(int x, int y);
}
interface calc_mul
{
int mul(int r, int s);
}
interface calc_div
{
int div(int c, int d);
}
class Calculation : calc_add, calc_sub, calc_mul, calc_div
{
public int result1;
public int add(int a, int b)
{
return result1 = a + b;
}
public int result2;
public int sub(int x, int y)
{
return result2 = x - y;
}
public int result3;
public int mul(int r, int s)
{
return result3 = r * s;
}
public int result4;
public int div(int c, int d)
{
return result4 = c / d;
}

class Program
{
static void Main(string[] args)
{
Calculation c = new Calculation();
c.add(20, 10);
c.sub(20, 15);
c.mul(15, 2);
c.div(100, 10);
Console.WriteLine("Multiple Inheritance Using Interfaces :\n ");
Console.WriteLine("Addition: " + c.result1);
Console.WriteLine("Substraction: " + c.result2);
Console.WriteLine("Multiplication :" + c.result3);
Console.WriteLine("Division: " + c.result4);
Console.ReadKey();
}
}

24
Output:

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace delegate_calc
{
public delegate void calculator(int a,int b);
class math
{

public void add(int a, int b)


{
Console.WriteLine("Addition of two numbers is:{0}",a+b);
}
public void subtract(int a, int b)
{
Console.WriteLine("Subtraction of two numbers is:{0}",a - b);
}
public void multiply(int a, int b)
{

Console.WriteLine("multiplicaton of two numbers is:{0}",a * b);


}
public void divide(int a, int b)
{

Console.WriteLine("Divison of two numbers is:{0}",a /b);


}
}
class program
{
static void Main(string[] args)
{
int x,y;
Console.WriteLine("Enter the value of number you want to calculate:");
x=int .Parse(Console.ReadLine());
y=int .Parse(Console.ReadLine());
math m=new math();

calculator cal =new calculator(m.add);


cal += new calculator(m.subtract);
cal += new calculator(m.multiply);
cal += new calculator(m.divide);
cal(x,y);
Console.ReadLine();

}
}
}

26
Output:

27
14. Write a program to get the user’s name from the console and print it
using different namespace.
using System;

namespace print_name1
{
class first
{
public void display1(string txt)
{
Console.WriteLine("Using first namespace:");
Console.WriteLine(txt);

}
}
}
namespace print_name2
{
class second
{
public void display2(string txt)
{
Console.WriteLine("Using second namespace");
Console.WriteLine(txt);
}
}
}

namespace Test
{
class third
{
public static void Main(string[] args)
{

Console.WriteLine("Enter Your name:");


string name=Console.ReadLine();
print_name1.first ob1=new print_name1.first();
ob1.display1(name);
print_name2.second ob2=new print_name2.second();
ob2.display2(name);
Console.ReadLine();

}
}
}

28
15. Write a program to implement Indexer.

using System;

namespace Indexer
{
public class year
{
public int[] arr = new int[5];
public int this[int year]
{
get { return arr[year];}
set { arr[year] = value;}
}
}
class Program
{
static void Main(string[] args)
{
year ob=new year();

Console.WriteLine("Enter year wise marks:");


Console.WriteLine("Enter first year marks:");
ob[0]=int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second Year marks:");
ob[1]=int.Parse(Console.ReadLine());
Console.WriteLine("Enter third year marks:");
ob[2]=int.Parse(Console.ReadLine());
Console.WriteLine("Enter fourth Year marks:");
ob[3] = int.Parse(Console.ReadLine());

Console.WriteLine("The average is:");

int avg = (ob[4] + ob[3] + ob[2] + ob[1])/4;


Console.WriteLine(avg);
Console.ReadLine();
}
}
}

29
Output:

30
16. Write a program to design two interfaces that are having same name
methods how we can access these methods in another class.

using System;

namespace interface_eg
{
interface get_firstname
{
void setName();
}
interface get_lastname
{
void setName();
}
internal class fullname : get_firstname, get_lastname
{
void get_firstname.setName()
{
Console.WriteLine("Enter first name:");
string txt1 = Console.ReadLine();
Console.WriteLine("Your first name is:"+txt1);

}
void get_lastname.setName()
{
Console.WriteLine("Enter last name:");
string txt2 = Console.ReadLine();
Console.WriteLine("Your last name is:"+txt2);
}

static void Main(string[] args)


{
get_firstname ob= new fullname();
ob.setName();

get_lastname ob1 = new fullname();


ob1.setName();

Console.ReadLine();

}
}
}

31
Output:

32
17. Write a program to implement method overloading.
using System;

namespace method_overloading
{
internal class methodoveloading
{
public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}

public double Add(double a,


double b, double c)
{
double sum = a + b + c;
return sum;
}

public static void Main(String[] args)


{

methodoveloading ob = new methodoveloading();

int sum2 = ob.Add(10, 20, 30);


Console.WriteLine("sum of the three "
+ "integer value : " + sum2);
double sum3 = ob.Add(1.0, 2.0, 3.0);
Console.WriteLine("sum of the three "
+ "double value : " + sum3);

Console.ReadLine();

}
}
}

33
Output:

34
18. Write a program to implement method overriding.

using System;

class Vehicle
{
public virtual void Start()
{
Console.WriteLine("Starting the vehicle...");
}
}

class Car : Vehicle


{
public override void Start()
{
Console.WriteLine("Starting the car's engine...");
}

public void Accelerate()


{
Console.WriteLine("The car is accelerating.");
}
}

class Motorcycle : Vehicle


{
public override void Start()
{
Console.WriteLine("Starting the motorcycle's engine...");
}

public void Wheelie()


{
Console.WriteLine("Performing a wheelie with the motorcycle.");
}
}

class Program
{
static void Main()
{
Vehicle genericVehicle = new Vehicle();
Vehicle myCar = new Car();
Vehicle myMotorcycle = new Motorcycle();

genericVehicle.Start();
myCar.Start();
myMotorcycle.Start();

if (myCar is Car car)


{
car.Accelerate();
}

if (myMotorcycle is Motorcycle motorcycle)


{
motorcycle.Wheelie();
}

Console.ReadLine();
}
35
Output:

36
19. Write a program in C sharp to create a calculator in windows form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
double txt1=Convert.ToDouble(textBox1.Text);
double txt2=Convert.ToDouble(textBox2.Text);
double sum= txt1+txt2;

textBox3.Text=sum.ToString();

private void button2_Click(object sender, EventArgs e)


{
double txt1 = Convert.ToDouble(textBox1.Text);
double txt2 = Convert.ToDouble(textBox2.Text);
double sum = txt1 - txt2;

textBox3.Text = sum.ToString();

private void button3_Click(object sender, EventArgs e)


{
double txt1 = Convert.ToDouble(textBox1.Text);
double txt2 = Convert.ToDouble(textBox2.Text);
double sum = txt1 * txt2;

textBox3.Text = sum.ToString();

private void button4_Click(object sender, EventArgs e)


{
double txt1 = Convert.ToDouble(textBox1.Text);
double txt2 = Convert.ToDouble(textBox2.Text);
double sum = txt1 / txt2;

textBox3.Text = sum.ToString();

}
}
}

37
20. 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.

using System;
using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;

namespace EmployeeManagement
{
public partial class EmployeeManagementForm : Form
{
private SQLiteConnection dbConnection;

public EmployeeManagementForm()
{
InitializeComponent();
dbConnection = new SQLiteConnection("Data Source=EmployeeDatabase.db;Version=3;");
dbConnection.Open();
CreateEmployeeTable();
LoadEmployeeData();
}

private void CreateEmployeeTable()


{
string createTableQuery = "CREATE TABLE IF NOT EXISTS Employees (" +
"EmpId INTEGER PRIMARY KEY AUTOINCREMENT," +
"FirstName TEXT," +
"LastName TEXT," +
"Gender TEXT," +
"ContactNo TEXT," +
"Designation TEXT," +
"Address TEXT," +
"Pin TEXT)";
SQLiteCommand createTableCommand = new SQLiteCommand(createTableQuery, dbConnection);
createTableCommand.ExecuteNonQuery();
}

private void LoadEmployeeData()


{
string selectQuery = "SELECT * FROM Employees";
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(selectQuery, dbConnection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}

private void buttonAdd_Click(object sender, EventArgs e)


{
string insertQuery = "INSERT INTO Employees (FirstName, LastName, Gender, ContactNo, Designation, Address, Pin) "
+
"VALUES (@FirstName, @LastName, @Gender, @ContactNo, @Designation, @Address, @Pin)";

38
insertCommand.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
insertCommand.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
insertCommand.Parameters.AddWithValue("@Gender", textBoxGender.Text);
insertCommand.Parameters.AddWithValue("@ContactNo", textBoxContactNo.Text);
insertCommand.Parameters.AddWithValue("@Designation", textBoxDesignation.Text);
insertCommand.Parameters.AddWithValue("@Address", textBoxAddress.Text);
insertCommand.Parameters.AddWithValue("@Pin", textBoxPin.Text);
insertCommand.ExecuteNonQuery();
LoadEmployeeData();
}

private void buttonUpdate_Click(object sender, EventArgs e)


{
if (dataGridView1.SelectedRows.Count > 0)
{
string updateQuery = "UPDATE Employees " +
"SET FirstName = @FirstName, LastName = @LastName, Gender = @Gender, " +
"ContactNo = @ContactNo, Designation = @Designation, Address = @Address, Pin = @Pin " +
"WHERE EmpId = @EmpId";
SQLiteCommand updateCommand = new SQLiteCommand(updateQuery, dbConnection);
updateCommand.Parameters.AddWithValue("@EmpId", dataGridView1.SelectedRows[0].Cells["EmpId"].Value);
updateCommand.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
updateCommand.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
updateCommand.Parameters.AddWithValue("@Gender", textBoxGender.Text);
updateCommand.Parameters.AddWithValue("@ContactNo", textBoxContactNo.Text);
updateCommand.Parameters.AddWithValue("@Designation", textBoxDesignation.Text);
updateCommand.Parameters.AddWithValue("@Address", textBoxAddress.Text);
updateCommand.Parameters.AddWithValue("@Pin", textBoxPin.Text);
updateCommand.ExecuteNonQuery();
LoadEmployeeData();
}
}

private void buttonDelete_Click(object sender, EventArgs e)


{
if (dataGridView1.SelectedRows.Count > 0)
{
string deleteQuery = "DELETE FROM Employees WHERE EmpId = @EmpId";
SQLiteCommand deleteCommand = new SQLiteCommand(deleteQuery, dbConnection);
deleteCommand.Parameters.AddWithValue("@EmpId", dataGridView1.SelectedRows[0].Cells["EmpId"].Value);
deleteCommand.ExecuteNonQuery();
LoadEmployeeData();
}
}

private void EmployeeManagementForm_FormClosing(object sender, FormClosingEventArgs e)


{
dbConnection.Close();
}
}
}

39
21. 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.
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace MyDbApplication
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)


{
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Path\To\MyDb.accdb";

using (OleDbConnection connection = new OleDbConnection(connectionString))


{
connection.Open();
string query = "SELECT FirstName FROM Employees";
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader["FirstName"].ToString());
}
}
}
}
}
}

40
Output:

41
22. Write a program using ADO.net to insert, update, delete data in back
end.
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
static string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabase;Integrated Security=True"; //
Replace with your SQL Server connection string

static void Main(string[] args)


{
while (true)
{
Console.WriteLine("Choose an option:");
Console.WriteLine("1. Insert Data");
Console.WriteLine("2. Update Data");
Console.WriteLine("3. Delete Data");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice: ");
int choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
InsertData();
break;
case 2:
UpdateData();
break;
case 3:
DeleteData();
break;
case 4:
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}

static void InsertData()


{
Console.Write("Enter first name: ");
string firstName = Console.ReadLine();
Console.Write("Enter last name: ");
string lastName = Console.ReadLine();
Console.Write("Enter department: ");
string department = Console.ReadLine();

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string insertQuery = "INSERT INTO Employees (FirstName, LastName, Department) VALUES (@FirstName,
@LastName, @Department)";
SqlCommand command = new SqlCommand(insertQuery, connection);
42
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted.");
}
}

static void UpdateData()


{
Console.Write("Enter employee ID to update: ");
int employeeID = int.Parse(Console.ReadLine());
Console.Write("Enter new department: ");
string newDepartment = Console.ReadLine();

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string updateQuery = "UPDATE Employees SET Department = @Department WHERE EmployeeID = @EmployeeID";
SqlCommand command = new SqlCommand(updateQuery, connection);

command.Parameters.AddWithValue("@EmployeeID", employeeID);
command.Parameters.AddWithValue("@Department", newDepartment);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) updated.");
}
}

static void DeleteData()


{
Console.Write("Enter employee ID to delete: ");
int employeeID = int.Parse(Console.ReadLine());

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string deleteQuery = "DELETE FROM Employees WHERE EmployeeID = @EmployeeID";


SqlCommand command = new SqlCommand(deleteQuery, connection);

command.Parameters.AddWithValue("@EmployeeID", employeeID);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) deleted.");
}
}
}

43
Output:
Choose an option:
1. Insert Data
2. Update Data
3. Delete Data
4. Exit
Enter your choice: 1
Enter first name: John
Enter last name: Doe
Enter department: HR
1 row(s) inserted.

Choose an option:
1. Insert Data
2. Update Data
3. Delete Data
4. Exit
Enter your choice: 2
Enter employee ID to update: 1
Enter new department: IT
1 row(s) updated.

Choose an option:
1. Insert Data
2. Update Data
3. Delete Data
4. Exit

44
Enter your choice: 3
Enter employee ID to delete: 1
1 row(s) deleted.

Choose an option:
1. Insert Data
2. Update Data
3. Delete Data
4. Exit
Enter your choice: 4

45
23. Display the data from the table in a DataGridView control using
dataset.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

class Program
{
static string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabase;Integrated Security=True"; //
Replace with your SQL Server connection string

static void Main(string[] args)


{
while (true)
{
Console.WriteLine("Choose an option:");
Console.WriteLine("1. Insert Data");
Console.WriteLine("2. Update Data");
Console.WriteLine("3. Delete Data");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice: ");
int choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
InsertData();
break;
case 2:
UpdateData();
break;
case 3:
DeleteData();
break;
case 4:
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}

static void InsertData()


{
Console.Write("Enter first name: ");
string firstName = Console.ReadLine();
Console.Write("Enter last name: ");
string lastName = Console.ReadLine();
Console.Write("Enter department: ");
string department = Console.ReadLine();

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string insertQuery = "INSERT INTO Employees (FirstName, LastName, Department) VALUES (@FirstName,
@LastName, @Department)";
46
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted.");
}
}

static void UpdateData()


{
Console.Write("Enter employee ID to update: ");
int employeeID = int.Parse(Console.ReadLine());
Console.Write("Enter new department: ");
string newDepartment = Console.ReadLine();

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string updateQuery = "UPDATE Employees SET Department = @Department WHERE EmployeeID = @EmployeeID";
SqlCommand command = new SqlCommand(updateQuery, connection);

command.Parameters.AddWithValue("@EmployeeID", employeeID);
command.Parameters.AddWithValue("@Department", newDepartment);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) updated.");
}
}

static void DeleteData()


{
Console.Write("Enter employee ID to delete: ");
int employeeID = int.Parse(Console.ReadLine());

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string deleteQuery = "DELETE FROM Employees WHERE EmployeeID = @EmployeeID";


SqlCommand command = new SqlCommand(deleteQuery, connection);

command.Parameters.AddWithValue("@EmployeeID", employeeID);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) deleted.");
}
}
}
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DisplayDataWithDataSet
{
public partial class MainForm : Form
{
private DataSet dataSet = new DataSet();
private BindingSource bindingSource = new BindingSource();

public MainForm()
{
InitializeComponent();
// Set up the binding source and add it to the DataGridView.
bindingSource.DataSource = dataSet;
47
LoadData();
}

private void LoadData()


{
// Replace with your connection string.
string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabase;Integrated Security=True";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string query = "SELECT * FROM YourTable"; // Replace with your table name

using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))


{
// Clear the dataset before filling it.
dataSet.Clear();

// Fill the dataset with data from the database.


adapter.Fill(dataSet, "Table");
}
}
}

}
}

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

Html
<asp:Label ID="lblUsername" runat="server" Text="Username:"></asp:Label>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvUsername" runat="server"
ControlToValidate="txtUsername" ErrorMessage="Username is required."
ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>
<br /><br />

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


<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Email is required." ForeColor="Red"
Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Invalid email format." ForeColor="Red"
Display="Dynamic" ValidationExpression="^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\
w+)*$"></asp:RegularExpressionValidator>
<br /><br />

<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."
ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>

49
<br /><br />

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


OnClick="btnRegister_Click" />

C sharp
protected void btnRegister_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Perform user registration logic here
// For simplicity, we'll just display a message
Response.Write("Registration successful!");
}
}

50
25. Display the data from the table in a Repeater control using dataset in
ASP.net.

Html
<asp:Repeater ID="repeaterEmployees" runat="server">
<ItemTemplate>
<div>
<strong>Employee ID:</strong> <%# Eval("EmployeeID") %><br />
<strong>First Name:</strong> <%# Eval("FirstName") %><br />
<strong>Last Name:</strong> <%# Eval("LastName") %><br />
<strong>Department:</strong> <%# Eval("Department") %><br />
<hr />
</div>
</ItemTemplate>
</asp:Repeater>

C Sharp
using System;
using System.Data;
using System.Data.SqlClient;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Simulated data retrieval using a DataTable (replace with actual data retrieval)
DataTable employeeData = GetEmployeeData();

if (employeeData.Rows.Count > 0)
{
repeaterEmployees.DataSource = employeeData;
repeaterEmployees.DataBind();
}
}
}

51
table.Columns.Add("EmployeeID", typeof(int));
table.Columns.Add("FirstName", typeof(string));
table.Columns.Add("LastName", typeof(string));
table.Columns.Add("Department", typeof(string));

table.Rows.Add(1, "John", "Doe", "HR");


table.Rows.Add(2, "Jane", "Smith", "IT");
table.Rows.Add(3, "Alice", "Johnson", "Finance");

return table;
}
}

52
Output:

53

You might also like