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

C# Lab File

The document contains a Python programming practical file with assignments on various Python programming tasks. It includes 27 assignments on topics like strings, lists, tuples, dictionaries, sets and more. The assignments range from basic operations to more advanced tasks like Caesar cipher encryption.

Uploaded by

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

C# Lab File

The document contains a Python programming practical file with assignments on various Python programming tasks. It includes 27 assignments on topics like strings, lists, tuples, dictionaries, sets and more. The assignments range from basic operations to more advanced tasks like Caesar cipher encryption.

Uploaded by

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

SHRI GURU RAM RAI UNIVERSITY

Practical File
BCA-P51
Python Programming
Course :- BCA
Semester :- 5th
(School of CA & IT)

Submitted to:-
Submitted by:-
Mr. Gagandeep Makkar
Shristi Goyal
Designation-Associate
Enroll no:-R210529061
Professor
INDEX
Page
S.No. Assignment Name / Practical Name
No.
Write a Python program to count the number of characters in
1. 1
a string. Sample String : ‘google.com’
Write a python program to get a single string from two given
2. strings, separated by a space and swap the first two characters 2
of each string.
Write a python program to add ‘ing’ at the end of a given
3. 3
string
Write a python program to find the first appearance of the
substring ‘not’ and ‘poor’ from a given string, if ‘not’ follows
4. 4
the ‘poor’, replace the whole ‘not’ …’poor’ substring with
‘good’ . return the resulting string.
Write a python program to create a Caesar a encryption. It is a
type of substitution cipher in which each letter in the plaintext
is replaced by a letter some fixed number of position down the
5. alphabet .for example with a left shift of 3,D would be 5
replaced by A,E would become B, and so on. The method is
named after Julius Caesar ,who used it in his private
correspondence .
Write a python that accepts a comma separated sequence of
6. words as input and prints the unique words in sorted from 6
(alphanumerically).
Write a python function to covert a given strings to all
7. uppercase if it contains at least 2 uppercase characters in the 7
first 4 characters.

Write a python program to get the largest and second largest


8. number from a list. 8

Write a python program to count the number of strings where


9. the string length is 2 or more and the first and last character 9
are same from a given list of strings.
Write a python program to get the difference between the
10. 10
two lists.
11. Write a Python program to get unique values from a list. 11

Write a Python program to get the frequency of the elements


12. 12
in a list.
13. Write a Python program to find common items from two lists. 13

Write a Python program to find the list in a list of lists whose


14. 14
sum of elements is the highest.
Write a Python program to add member(s) in a set and iterate
15. 15
over it.
Write a Python program to apply union, intersection,
16. 16
difference, symmetric difference operators on sets.
Write a Python program to check if a set is a subset of another
17. 17
set.
Wrote a Python program to check if two given sets have no
18. 18
elements in common.
Write a Python program to remove an item from a set if it is
19. 19
present in the set.
Write a Python program to remove the intersection of a 2nd set
20. 20
from the 1st set.
Write a Python script to sort(ascending and descending) a
21. 21
dictionary by value.
Write a Python script to concatenate following dictionaries to
22. 22
create a new one.
23. Write a Python script to merge two Python dictionaries. 23

Write a Python program to combine two dictionary adding


24. 24
values for common keys.
25. Write a Python program to get the top three items in a shop. 25

Write a Python program to find the highest 3 values in a


26. 26
dictionary.
Write a python script to generate and print a dictionary that
27. 27
contains a number(between 1 and n) in the form(x,x*x).
Write a Python function to sum all the numbers in a
28. 28
list.Sample List: (8,2,3,0,7)
29. Write a Python program to reverse a string. 29

Write a Python function to calculate the factorial of a number


(a non- negative integer). The function accepts the number as
30. 30
an argument.

31. Write a Python function that accepts a string and calculate the 31
number of upper case letters and lower case letters.

32. Write a Python function to check whether a string is a pangram 32


or not.

33. Write a Python program to convert a given tuple of positive 33


integers into an integer.

34. Swap the following two tuples 34


t1=(1,2)
t2=(3,4)

35. Write a Python program to check if a specified element 35


presents in a tuple of tuples.

36. Write a Python program to convert a given list of tuples to a list 36


of lists.

37. Write a Python program to capitalize first and last letters of 37


each word of a given string.
38. Write a Python program to count and display the vowels of a 38
given text.
39. Write a Python program to remove the K'th element from a 39
given list, print the new list.

40. Write a Python program to calculate the average value of 40


the numbers in a given tuple of tuples.

41. Write a Python program to count repeated characters in a 41


string.
42. Write a Python program to filter a dictionary based on values. 42

Q1. 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;

class Program
{
static bool IsPrime(int number)
{
if (number <= 1)
{
return false;
}

for (int i = 2; i <= Math.Sqrt(number); i++)


{
if (number % i == 0)
{
return false;
}
}

return true;
}

static void Main(string[] args)


{
Console.WriteLine("Prime numbers between 1 and 200:");

for (int i = 1; i <= 200; i++)


{
if (IsPrime(i))
{
Console.Write(i);

// Print comma after the prime number if it's not the last one
if (i != 200)
{
Console.Write(", ");
}
}
}
}
}
Output
Prime numbers between 1 and 200:
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 using System.

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Armstrong numbers between 1 and 1000:");
for (int num = 1; num <= 1000; num++)
{
int originalNumber, remainder, result = 0;
originalNumber = num;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += (int)Math.Pow(remainder, 3); // 3 is the number of digits for Armstrong
number
originalNumber /= 10;
}
if (result == num)
{
Console.WriteLine(num);
}
}
}
}

Output
Armstrong numbers between 1 and 1000:
1
2
3
4
5
6
7
8
9
153
370
371
407
Q3. Write a C sharp program using loop that examines all the numbers
between 2 and 1000, and displays only Perfect number (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;
class Program
{
static void Main()
{
Console.WriteLine("Perfect numbers between 2 and 1000:");
for (int number = 2; number <= 1000; number++)
{
if (IsPerfectNumber(number))
{
Console.WriteLine(number);
}
}
}

static bool IsPerfectNumber(int number)


{
int sum = 1; // Start with 1 because every number is divisible by 1

for (int i = 2; i <= Math.Sqrt(number); i++)


{
if (number % i == 0)
{
// If 'i' is a divisor, add it to the sum
sum += i;

// If 'i' is not the square root of the number, add the corresponding divisor
if (i != number / i)
{
sum += number / i;
}
}
}

// If the sum of divisors equals the number itself, it's a perfect number
return sum == number;
}
}

Output
Perfect numbers between 2 and 1000:
6
28
496

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

using System;

class Program
{
static void Main()
{
int[] numbers = new int[10];

// Accepting input from the user


Console.WriteLine("Enter 10 integers:");
for (int i = 0; i < 10; i++)
{
Console.Write($"Enter number {i + 1}: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}

// Sorting the array in ascending order using Bubble Sort


for (int i = 0; i < numbers.Length - 1; i++)
{
for (int j = 0; j < numbers.Length - 1 - i; j++)
{
if (numbers[j] > numbers[j + 1])
{
// Swap numbers[j] and numbers[j + 1]
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
// Printing the sorted array
Console.WriteLine("Sorted numbers in ascending order:");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
}
}
Output
Enter 10 integers:
Enter number 1: 5
Enter number 2: 2
Enter number 3: 9
Enter number 4: 1
Enter number 5: 7
Enter number 6: 3
Enter number 7: 8
Enter number 8: 4
Enter number 9: 6
Enter number 10: 10
Sorted numbers in ascending order:
1 2 3 4 5 6 7 8 9 10

Q5. Write a program to implement the concept of abstract class using System.

// Abstract class definition


abstract class Shape
{
// Abstract method declaration
public abstract double CalculateArea();
}
// Derived class that inherits from the abstract class
class Circle : Shape
{
private double radius;
// Constructor
public Circle(double r)
{
radius = r;
}
// Implementation of the abstract method from the base abstract class
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
}
class Program
{
static void Main()
{
// Creating an instance of the derived class
Circle circle = new Circle(5);
// Calling the abstract method from the derived class
double area = circle.CalculateArea();
// Printing the calculated area
Console.WriteLine("Area of the circle: " + area);
}
}

Output
Area of the circle: 78.53981633974483

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

// Sealed class definition


sealed class SealedClass
{
public void Display()
{
Console.WriteLine("This is a sealed class.");
}
}

// This line will result in a compilation error since you cannot inherit from a sealed
class
// class DerivedClass : SealedClass { }

class Program
{
static void Main()
{
// Creating an instance of the sealed class
SealedClass sealedObj = new SealedClass();
sealedObj.Display();
}
}

Output
This is a sealed class.

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

class Program
{
static void Main()
{
// Jagged array declaration and initialization
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

// Displaying jagged array elements using foreach loop


Console.WriteLine("Jagged Array Elements:");
foreach (int[] innerArray in jaggedArray)
{
foreach (int number in innerArray)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
}
}

Output
Jagged Array Elements:
123
45
6789

Q8. 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 returns 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, containing 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
{
// Properties
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; }

// Methods
public double CalculateGrossSalary()
{
double DA = 0.56 * BasicSalary;
double HRA = 0.2 * BasicSalary;
return BasicSalary + DA + HRA;
}

public double CalculateNetSalary()


{
double PF = 780;
double incomeTax = 0;
if (Grade == 'A')
{
incomeTax = 2000;
}
else if (Grade == 'B')
{
incomeTax = 1500;
}
else if (Grade == 'C')
{
incomeTax = 1000;
}
return CalculateGrossSalary() - (PF + incomeTax);
}

public void PrintPaySlip()


{
Console.WriteLine($"Employee ID: {EmpId}");
Console.WriteLine($"Name: {FirstName} {LastName}");
Console.WriteLine($"Address: {Address}, {PinCode}");
Console.WriteLine($"Contact Number: {ContactNumber}");
Console.WriteLine($"Grade: {Grade}");
Console.WriteLine($"Basic Salary: {BasicSalary}");
Console.WriteLine($"Gross Salary: {CalculateGrossSalary()}");
Console.WriteLine($"Net Salary: {CalculateNetSalary()}");
}
}

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

// Printing pay slip


Console.WriteLine("Pay Slip:");
Console.WriteLine("---------");
employee.PrintPaySlip();
}
}

Output
Pay Slip:
---------
Employee ID: 1
Name: John Doe
Address: 123 Main St, 12345
Contact Number: 9876543210
Grade: B
Basic Salary: 15000
Gross Salary: 30000
Net Salary: 28220

Q9. Write a program to demonstrate boxing and unboxing.

using System;

class Program
{
static void Main()
{
// Boxing: Converting value type to reference type
int intValue = 42;
object boxedValue = intValue; // Boxing
// Unboxing: Converting reference type back to value type
int unboxedValue = (int)boxedValue; // Unboxing

Console.WriteLine($"Original Value: {intValue}");


Console.WriteLine($"Boxed Value: {boxedValue}");
Console.WriteLine($"Unboxed Value: {unboxedValue}");
}
}

Output
Original Value: 42
Boxed Value: 42
Unboxed Value: 42

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


entered string.

using System;
class Program
{
static void Main()
{
Console.Write("Enter a string: ");
string inputString = Console.ReadLine();
int digitCount = 0;
int charCount = 0;
int punctuationCount = 0;
foreach (char c in inputString)
{
if (char.IsDigit(c))
{
digitCount++;
}
else if (char.IsLetter(c))
{
charCount++;
}
else if (char.IsPunctuation(c) || char.IsSymbol(c))
{
punctuationCount++;
}
}

Console.WriteLine($"Number of Digits: {digitCount}");


Console.WriteLine($"Number of Characters: {charCount}");
Console.WriteLine($"Number of Punctuation Marks: {punctuationCount}");
}
}

Output
Enter a string: Hello, World! 123
Number of Digits: 3
Number of Characters: 10
Number of Punctuation Marks: 2

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

using System;
class Program
{
static void Main()
{
try
{
// Code that may cause an exception
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
int result = 10 / number; // This line may cause a DivideByZeroException if the
number is 0
Console.WriteLine($"Result of 10 divided by {number} is: {result}");
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero. Please enter a non-zero number.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}

Output
Case 1: Invalid input (non-numeric):
Enter a number: ABC
Invalid input. Please enter a valid number.
Case 2: Dividing by zero:
Enter a number: 0
Cannot divide by zero. Please enter a non-zero number.
Case 3: Valid input (non-zero):
Enter a number: 2
Result of 10 divided by 2 is: 5
Q12. Write a program to implement multiple inheritances using interface.

using System;
// First interface
interface IShape
{
void Draw();
}

// Second interface
interface IColor
{
void FillColor();
}

// Class implementing both interfaces


class Circle : IShape, IColor
{
public void Draw()
{
Console.WriteLine("Drawing Circle");
}

public void FillColor()


{
Console.WriteLine("Filling Circle with color");
}
}

class Program
{
static void Main()
{
// Creating an object of the class implementing multiple interfaces
Circle circle = new Circle();

// Calling methods from both interfaces


circle.Draw();
circle.FillColor();
}
}
Output
Drawing Circle
Filling Circle with color
Q13. Write a program in C# using a delegate to perform basic arithmetic
operations like addition, subtraction, division, and multiplication.

using System;

// Delegate declaration for arithmetic operations


delegate double ArithmeticOperation(double num1, double num2);

class Program
{
static void Main()
{
// Creating delegate instances for different arithmetic operations
ArithmeticOperation add = (num1, num2) => num1 + num2;
ArithmeticOperation subtract = (num1, num2) => num1 - num2;
ArithmeticOperation multiply = (num1, num2) => num1 * num2;
ArithmeticOperation divide = (num1, num2) =>
{
if (num2 != 0)
{
return num1 / num2;
}
else
{
Console.WriteLine("Cannot divide by zero.");
return double.NaN;
}
};
// Taking input from the user
Console.Write("Enter first number: ");
double number1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second number: ");
double number2 = Convert.ToDouble(Console.ReadLine());

// Performing arithmetic operations using delegates


Console.WriteLine($"Sum: {add(number1, number2)}");
Console.WriteLine($"Difference: {subtract(number1, number2)}");
Console.WriteLine($"Product: {multiply(number1, number2)}");
Console.WriteLine($"Quotient: {divide(number1, number2)}");
}
}
Output
Enter first number: 10
Enter second number: 5
Sum: 15
Difference: 5
Product: 50
Quotient: 2
Q14. Write a program to get the user’s name from the console and print it
using different namespace.

First, create a class in one namespace called InputHandler to handle user input:
namespace InputNamespace
{
public class InputHandler
{
public static string GetUserName()
{
Console.Write("Enter your name: ");
return Console.ReadLine();
}
}
}
Second, create another class in a different namespace called OutputHandler to handle
output operations:
namespace OutputNamespace
{
public class OutputHandler
{
public static void PrintUserName(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
}
Finally, use these classes in your main program:
using System;
using InputNamespace;
using OutputNamespace;

class Program
{
static void Main()
{
string userName = InputHandler.GetUserName();
OutputHandler.PrintUserName(userName);
}
}

Output
Enter your name: John
Hello, John!
Q15. Write a program to implement Indexer.

using System;

class MyCollection
{
private string[] items = new string[5];

// Indexer declaration
public string this[int index]
{
get
{
if (index >= 0 && index < items.Length)
{
return items[index];
}
else
{
return "Index out of range";
}
}
set
{
if (index >= 0 && index < items.Length)
{
items[index] = value;
}
else
{
Console.WriteLine("Index out of range");
}
}
}
}

class Program
{
static void Main()
{
MyCollection collection = new MyCollection();

// Setting values using indexer


collection[0] = "Item 1";
collection[1] = "Item 2";
collection[2] = "Item 3";

// Getting values using indexer and displaying the output


Console.WriteLine(collection[0]);
Console.WriteLine(collection[1]);
Console.WriteLine(collection[2]);
Console.WriteLine(collection[3]); // This will display "Index out of range"
}
}
Output
Item 1
Item 2
Item 3
Index out of range

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

using System;

// First interface
interface IInterface1
{
void CommonMethod();
}

// Second interface with the same method name as in the first interface
interface IInterface2
{
void CommonMethod();
}

// Class implementing both interfaces


class MyClass : IInterface1, IInterface2
{
// Explicit interface implementation for IInterface1
void IInterface1.CommonMethod()
{
Console.WriteLine("Method from IInterface1");
}

// Explicit interface implementation for IInterface2


void IInterface2.CommonMethod()
{
Console.WriteLine("Method from IInterface2");
}
}

class Program
{
static void Main()
{
// Creating an object of the class
MyClass myClass = new MyClass();

// Accessing methods from interfaces using explicit interface implementation


((IInterface1)myClass).CommonMethod();
((IInterface2)myClass).CommonMethod();
}
}

Output
Method from IInterface1
Method from IInterface2
Q17. Write a program to implement method overloading.

using System;

class Calculator
{
// Method to add two integers
public int Add(int num1, int num2)
{
return num1 + num2;
}

// Method to add three integers (method overloading)


public int Add(int num1, int num2, int num3)
{
return num1 + num2 + num3;
}
// Method to add two doubles (method overloading)
public double Add(double num1, double num2)
{
return num1 + num2;
}
}

class Program
{
static void Main()
{
Calculator calculator = new Calculator();

// Calling the overloaded methods and displaying the output


Console.WriteLine("Sum of 2 and 3 is: " + calculator.Add(2, 3));
Console.WriteLine("Sum of 2, 3, and 4 is: " + calculator.Add(2, 3, 4));
Console.WriteLine("Sum of 2.5 and 3.7 is: " + calculator.Add(2.5, 3.7));
}
}

Output
Sum of 2 and 3 is: 5
Sum of 2, 3, and 4 is: 9
Sum of 2.5 and 3.7 is: 6.2
Q18. Write a program to implement method overriding.

using System;

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}

class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}

class Program
{
static void Main()
{
Shape shape = new Shape();
shape.Draw(); // Calls base class method

Circle circle = new Circle();


circle.Draw(); // Calls derived class method (overrides base class method)
}
}

Output
Drawing a shape
Drawing a circle

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

First, create a new Windows Forms Application project in Visual Studio and design the form
with buttons for digits, operators, and a textbox to display input and results. Then, add
event handlers to the buttons to handle button clicks and perform calculations. Here's an
example of the code for a basic calculator:
using System;
using System.Windows.Forms;

namespace CalculatorApp
{
public partial class CalculatorForm : Form
{
private string currentInput = string.Empty;
private string operatorSymbol = string.Empty;
private double firstNumber = 0;

public CalculatorForm()
{
InitializeComponent();
}

private void DigitButtonClick(object sender, EventArgs e)


{
Button button = (Button)sender;
currentInput += button.Text;
textBoxResult.Text = currentInput;
}

private void OperatorButtonClick(object sender, EventArgs e)


{
Button button = (Button)sender;
operatorSymbol = button.Text;
firstNumber = double.Parse(currentInput);
currentInput = string.Empty;
}

private void EqualButtonClick(object sender, EventArgs e)


{
double secondNumber = double.Parse(currentInput);
double result = 0;

switch (operatorSymbol)
{
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
if (secondNumber != 0)
{
result = firstNumber / secondNumber;
}
else
{
MessageBox.Show("Cannot divide by zero.");
currentInput = string.Empty;
textBoxResult.Text = string.Empty;
return;
}
break;
}

currentInput = result.ToString();
textBoxResult.Text = currentInput;
}

private void ClearButtonClick(object sender, EventArgs e)


{
currentInput = string.Empty;
operatorSymbol = string.Empty;
firstNumber = 0;
textBoxResult.Text = string.Empty;
}
}
}

Output
This code assumes that you have created a Windows Forms application with buttons
for digits (0-9), operators (+, -, *, /), an equal button (=), and a clear button (C). The
‘DigitButtonClick’, ‘OperatorButtonClick’, ‘EqualButtonClick’, and ‘ClearButtonClick’
methods handle button clicks and perform calculations accordingly.
Q20. 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.

1. Design the User Interface:


Create a Windows Forms application with the following controls:

TextBoxes for EmpId, First Name, Last Name, Contact No, Designation, Address, and
Pin.
RadioButton or ComboBox for Gender selection.
Buttons for Add, Update, and Delete operations.
2. Set Up the Database:
Create a SQL Server database with a table named Employees that has columns for
EmpId, FirstName, LastName, Gender, ContactNo, Designation, Address, and Pin. Set
EmpId as the primary key.

3. Implement Database Operations:


You will need to use ADO.NET or an Object-Relational Mapper (ORM) like Entity
Framework to interact with the database. Here's an example of how you can use
ADO.NET to perform database operations:
using System;
using System.Data.SqlClient;

namespace EmployeeManagementApp
{
public class DatabaseHelper
{
private const string ConnectionString = "Data Source=YourServer;Initial
Catalog=YourDatabase;Integrated Security=True";

public void AddEmployee(Employee employee)


{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string query = "INSERT INTO Employees (EmpId, FirstName, LastName, Gender,
ContactNo, Designation, Address, Pin) " +
"VALUES (@EmpId, @FirstName, @LastName, @Gender, @ContactNo,
@Designation, @Address, @Pin)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@EmpId", employee.EmpId);
command.Parameters.AddWithValue("@FirstName", employee.FirstName);
command.Parameters.AddWithValue("@LastName", employee.LastName);
command.Parameters.AddWithValue("@Gender", employee.Gender);
command.Parameters.AddWithValue("@ContactNo", employee.ContactNo);
command.Parameters.AddWithValue("@Designation", employee.Designation);
command.Parameters.AddWithValue("@Address", employee.Address);
command.Parameters.AddWithValue("@Pin", employee.Pin);
command.ExecuteNonQuery();
}
}
}
// Implement methods for updating and deleting records similarly
}
}

Output
4. Handle Button Click Events:
In the form's code-behind file, handle the button click events to call the appropriate
methods from the ‘DatabaseHelper’ class.

Q21. 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.

1. Set Up the Database:

Create a SQL Server database named MyDb and a table named Employees with
columns EmpId, FirstName, LastName, Gender, ContactNo, Designation, Address, and
Pin.

2. Windows Forms Application:

Design your Windows Forms application with a ListBox control to display the data.

3. Code to Connect to Database and Populate ListBox:


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

namespace EmployeeListApp
{
public partial class MainForm : Form
{
private const string ConnectionString = "Data Source=YourServer;Initial
Catalog=MyDb;Integrated Security=True";

public MainForm()
{
InitializeComponent();
PopulateEmployeeListBox();
}

private void PopulateEmployeeListBox()


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

string query = "SELECT * FROM Employees";


using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string employeeInfo = $"{reader["EmpId"]} - {reader["FirstName"]}
{reader["LastName"]}";
listBoxEmployees.Items.Add(employeeInfo);
}
}
}
}
}
}
}

Output
When you run the application, the listBoxEmployees will be populated with
employee details retrieved from the Employees table in the MyDb database.

Q22. Write a program using ADO.net to insert, update, delete data in back
end.

using System;
using System.Data.SqlClient;

namespace DataManipulationApp
{
class Program
{
private const string ConnectionString = "Data Source=YourServer;Initial
Catalog=YourDatabase;Integrated Security=True";

static void Main()


{
Console.WriteLine("Data Manipulation Example");
// Insert Data
InsertEmployee("John", "Doe", "john@example.com");

// Display Employees
DisplayEmployees();

// Update Data
UpdateEmployee(1, "Updated John", "Doe", "updatedjohn@example.com");

// Display Employees after update


DisplayEmployees();

// Delete Data
DeleteEmployee(1);

// Display Employees after deletion


DisplayEmployees();

Console.WriteLine("Press any key to exit...");


Console.ReadKey();
}

static void InsertEmployee(string firstName, string lastName, string email)


{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string insertQuery = "INSERT INTO Employees (FirstName, LastName, Email) VALUES
(@FirstName, @LastName, @Email)";
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@Email", email);
command.ExecuteNonQuery();
Console.WriteLine("Employee inserted successfully.");
}
}
}
static void UpdateEmployee(int employeeId, string firstName, string lastName, string
email)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string updateQuery = "UPDATE Employees SET FirstName = @FirstName, LastName =
@LastName, Email = @Email WHERE EmployeeId = @EmployeeId";
using (SqlCommand command = new SqlCommand(updateQuery, connection))
{
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@Email", email);
command.Parameters.AddWithValue("@EmployeeId", employeeId);
command.ExecuteNonQuery();
Console.WriteLine("Employee updated successfully.");
}
}
}

static void DeleteEmployee(int employeeId)


{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string deleteQuery = "DELETE FROM Employees WHERE EmployeeId =
@EmployeeId";
using (SqlCommand command = new SqlCommand(deleteQuery, connection))
{
command.Parameters.AddWithValue("@EmployeeId", employeeId);
command.ExecuteNonQuery();
Console.WriteLine("Employee deleted successfully.");
}
}
}

static void DisplayEmployees()


{
Console.WriteLine("Employees:");
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string selectQuery = "SELECT EmployeeId, FirstName, LastName, Email FROM
Employees";
using (SqlCommand command = new SqlCommand(selectQuery, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeId"]}: {reader["FirstName"]}
{reader["LastName"]} - {reader["Email"]}");
}
}
}
}
Console.WriteLine();
}
}
}

Q23. 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;

namespace DataGridViewWithDataSet
{
public partial class MainForm : Form
{
private const string ConnectionString = "Data Source=YourServer;Initial
Catalog=YourDatabase;Integrated Security=True";

public MainForm()
{
InitializeComponent();
LoadDataIntoDataGridView();
}

private void LoadDataIntoDataGridView()


{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string selectQuery = "SELECT * FROM Employees";
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectQuery, connection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Employees");

// Set DataGridView DataSource to the DataSet


dataGridViewEmployees.DataSource = dataSet.Tables["Employees"];
}
}
}
}

Q24. Create a registration form in ASP.NET and use different types of


validation controls.
Q25. Display the data from the table in a Repeater control using dataset in
ASP.net.

You might also like