C# Vinay Practical File.
C# Vinay Practical File.
Write a C sharp program to generate prime numbers between 1 to 200 and also print to the console.
Program:- using System;
namespace PrimeNumber
{
class Program
{
public static void main(string[] args)
{
bool isPrime = true;
Console.WriteLine("Prime Numbers : ");
for (int i = 2; i <= 200; i++)
{
for (int j = 2; j <= 200; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.Write("\t" +i);
}
isPrime = true;
}
Console.ReadKey();
}
}
}
1
Output:
2
PROGRAM 2.
3
Output:
4
PROGRAM 3.
Write a C sharp program to accept an array of integers (10) and sort them in ascending order.
Program:- using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
Console.WriteLine("Enter 10 integers:");
Array.Sort(numbers);
5
Output:
6
PROGRAM 4.
Write a program to implement the concept of abstract class.
Program:- using System;
namespace Abstract
{
class Program
{
public static void main(string[] args)
{
B b = new B();
b.show();
b.display();
}
}
}
abstract class A
{
public abstract void show();
public void display()
{
Console.WriteLine("I am parent class.");
}
}
class B : A
{
public override void show()
{
Console.WriteLine("I am override method of abstract class.");
}
}
7
Output:
8
PROGRAM 5.
Write a program to implement the concept of sealed class.
Program:- using System;
namespace SealedConcept
{
class Program
{
public static void main(string[] args)
{
B b = new b();
b.show();
}
}
}
9
Output:
10
PROGRAM 6.
Write a C sharp program for jagged array and display its item through foreach loop.
Program:- using System; namespace JaggedArray
{
class Program
{
public static void main(string[] args)
{
int[][] member = new int[3][];
member[0] = new int[] { 1, 2, 3 };
member[1] = new int[] { 4, 5 };
member[2] = new int[] { 6, 7, 8, 9 };
11
Output:
12
PROGRAM 7.
Write a program to demonstrate boxing and unboxing.
Program:- using System;
class BoxingUnboxingDemo
{
static void Main()
{
int number = 42; // Value type
object boxed = number; // Boxing
Output:
13
14
PROGRAM 8.
Write a program to find number of digit, character, and punctuation in entered string.
Program:- using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
int digitCount = 0;
int charCount = 0;
int punctuationCount = 0;
foreach (char c in input)
{
if (char.IsDigit(c))
{
digitCount++;
}
else if (char.IsLetter(c))
{
charCount++;
}
else if (char.IsPunctuation(c))
{ punctuationCount++;
}
}
Console.WriteLine("\nResults:");
Console.WriteLine("Number of
Digits: " + digitCount);
Console.WriteLine("Number of
Characters: " + charCount);
Console.WriteLine("Number of
Punctuation Marks: " +
punctuationCount);
}
}
15
Input:
Output:
16
PROGRAM 9.
Write a program using C# for exception handling.
Program:- using System;
class ExceptionHandlingDemo
{
static void Main()
{
try
{
Console.WriteLine("Enter the first number:");
int num1 = Convert.ToInt32(Console.ReadLine());
17
Output:
18
PROGRAM 10.
Write a program to implement multiple inheritances using interface.
Program:- using System;
Console.WriteLine("\nEnd of demo.");
}
}
20
Output:
21
PROGRAM 11.
Write a program in C# using a delegate to perform basic arithmetic operations like addition,
subtraction, division, and multiplication.
Program:- using System;
namespace ArithmeticOperations
{
// Define a delegate that takes two double parameters and returns a double
public delegate double ArithmeticOperation(double a, double b);
class Program
{
// Methods for arithmetic operations
public static double Add(double a, double b)
{
return a + b;
}
// Example usage
double num1 = 10;
double num2 = 5;
23
Output:
24
PROGRAM 12:
Write a program to implement Indexer
Program:- using System;
// Indexer declaration
public string this[int index]
{
get
{
// Check for valid index
if (index < 0 || index >= elements.Length)
{
throw new IndexOutOfRangeException("Index out of range.");
}
return elements[index];
}
set
{
// Check for valid index
if (index < 0 || index >= elements.Length)
{
throw new IndexOutOfRangeException("Index out of range.");
}
elements[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
SampleCollection
25
// Getting values using the indexer
for (int i = 0; i < 4; i++)
{
Console.WriteLine(collection[i]);
}
Output:
26
PROGRAM 13.
Write a program to implement method overloading.
class Program
{
// Method to add two integers
public static int Add(int a, int b)
{
return a + b;
}
27
Output:
28
PROGRAM 14.
Write a program to implement method overriding.
Program:- using System;
namespace MethodOverridingExample
{
// Base class
class Animal
{
// Virtual method
public virtual void Speak()
{
Console.WriteLine("The animal makes a sound.");
}
}
// Derived class
class Dog : Animal
{
// Overriding the Speak method
public override void Speak()
{
Console.WriteLine("The dog barks.");
}
}
class Program
{
static void Main(string[] args)
{
// Creating instances of the derived classes
Animal myDog = new Dog();
Animal myCat = new Cat();
30
PROGRAM 15.
Write a program in C sharp to create a calculator in windows form.
Program:- using System;
using System.Windows.Forms;
namespace BasicCalculator
{
public partial class Form1 : Form
{
private double resultValue = 0;
private string operation = "";
private bool isOperationPerformed = false;
public Form1()
{
InitializeComponent();
}
isOperationPerformed = false;
Button button = (Button)sender;
textBoxResult.Text += button.Text;
}
31
case "+":
textBoxResult.Text = (resultValue + double.Parse(textBoxResult.Text)).ToString();
break;
case "-":
textBoxResult.Text = (resultValue - double.Parse(textBoxResult.Text)).ToString();
break;
case "*":
textBoxResult.Text = (resultValue * double.Parse(textBoxResult.Text)).ToString();
break;
case "/":
if (double.Parse(textBoxResult.Text) != 0)
{
textBoxResult.Text = (resultValue / double.Parse(textBoxResult.Text)).ToString();
}
else
{
MessageBox.Show("Cannot divide by zero");
}
break;
default:
break;
}
resultValue = double.Parse(textBoxResult.Text);
operation = "";
}
}
}
Output:
17
PROGRAM 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.
Program:-
Open Visual Studio and create a new Windows Forms App (.NET Framework) or Windows Forms App
(.NET 6/7/8).
Add Controls to Form:
TextBoxes: For EmpId, FirstName, LastName, Gender, ContactNo, Designation, Address, Pin
Buttons: Add, Update, Delete
DataGridView: To show the list of
employees Name your text boxes meaningfully:
txtEmpId, txtFirstName, txtLastName, txtGender, etc.
20
command.Parameters.AddWithValue("@EmpId", textBoxEmpId.Text);
command.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
command.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
command.Parameters.AddWithValue("@Gender",
comboBoxGender.SelectedItem.ToString());
command.Parameters.AddWithValue("@ContactNo", textBoxContactNo.Text);
command.Parameters.AddWithValue("@Designation", textBoxDesignation.Text);
command.Parameters.AddWithValue("@Address", textBoxAddress.Text);
command.Parameters.AddWithValue("@Pin", textBoxPin.Text);
command.ExecuteNonQuery();
}
LoadEmployees();
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
string query = "UPDATE employees SET FirstName=@FirstName, LastName=@LastName,
Gender=@Gender, ContactNo=@ContactNo, Designation=@Designation, Address=@Address,
Pin=@Pin WHERE EmpId=@EmpId";
using (SQLiteCommand command = new SQLiteCommand(query, connection))
{
command.Parameters.AddWithValue("@EmpId", textBoxEmpId.Text);
command.Parameters.AddWithValue("@FirstName", textBoxFirstName.Text);
command.Parameters.AddWithValue("@LastName", textBoxLastName.Text);
command.Parameters.AddWithValue("@Gender",
comboBoxGender.SelectedItem.ToString());
command.Parameters.AddWithValue("@ContactNo", textBoxContactNo.Text);
command.Parameters.AddWithValue("@Designation", textBoxDesignation.Text);
}
}
21
Output:
22
PROGRAM 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.
Program:-
GO
USE MyDb;
GO
FName VARCHAR(100),
LName VARCHAR(100),
Department VARCHAR(100),
);
OR
23
Step 2: Create a Windows Forms Application (C#)
o ListBox – listBoxName
o ListBox – listBoxPosition
using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
namespace MyDB
string connectionString =
"Server=YOUR_SERVER_NAME;Database=MyDb;Trusted_Connection=True;";
connection.Open();
listBoxFirstName.Items.Clear();
listBoxLastName.Items.Clear();
while (reader.Read())
24
listBoxFirstName.Items.Add(reader["FirstName"].ToString());
listBoxLastName.Items.Add(reader["LastName"].ToString());
Output:
25
PROGRAM 18.
Display the data from the table in a DataGridView control using dataset.
Program:-
GO
USE MyDb;
GO
StudentName VARCHAR(100),
Branch VARCHAR(50),
);
Step 2: Create a Windows Application and add DataGridView on the Form. Now add a DataGridView
control to the form by selecting it from Toolbox and set properties according to your needs.
26
Adding Source Code for GridView
EventArgs e) {
SqlDataAdapter da = new
da.Fill(ds, "Student");
dataGridView1.DataSource =
ds.Tables["Student"].DefaultView;
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsDataGrid
{ public Form1() {
InitializeComponent();
da.Fill(ds, "Student");
27
dataGridView1.DataSource = ds.Tables["Student"].DefaultView;
con.Open();
string qur = "INSERT INTO Student VALUES ('" + textBox1.Text + "','" + textBox2.Text +
"','" + textBox3.Text + "','" + textBox4.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
{ textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
28
Output:
29
PROGRAM 19.
Create a registration form in ASP.NET and use different types of validation controls.
Program:-
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<br />
Email :<asp:TextBox ID="txtEmail" placeholder="Enter Email"
runat="server"></asp:TextBox>
<br />
Mobile :<asp:TextBox ID="txtMobile" placeholder="Enter Mobile"
runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ErrorMessage="Mobile cannot be blank" ControlToValidate="txtMobile"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="txtMobile" ErrorMessage="Mobile number must be 10 digit"
ForeColor="Red" ValidationExpression="\d{10}"></asp:RegularExpressionValidator>
30
<br />
Password :<asp:TextBox ID="txtPassword" placeholder="Enter Password"
runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ErrorMessage="Password cannot be blank" ControlToValidate="txtPassword"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword"
ErrorMessage="Password and confiem password must be same"
ForeColor="Red"></asp:CompareValidator>
<br />
Confirm Password :<asp:TextBox ID="txtConfirmPassword" placeholder="Confirm
Password" runat="server"></asp:TextBox>
<br />
Age :<asp:TextBox ID="txtAge" placeholder="Enter Age"
runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ErrorMessage="Age cannot be blank" ControlToValidate="txtAge"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Age must
be between 18 to 40" ControlToValidate="txtAge" ForeColor="Red" MaximumValue="40"
MinimumValue="18"></asp:RangeValidator>
<br />
</body>
</html>
Code-Behind: Register.aspx.cs
31
[Required(ErrorMessage = "Mobile is required")]
[RegularExpression(@ "\d{10}", ErrorMessage = "Please enter 10 digit Mobile No.")]
public string mobile
{
get;
set;
}
Now add the following code on submit button click event; here we will do the server-side validation
for all the properties using data annotations:
reg.name = txtName.Text.ToString();
reg.email = txtEmail.Text.ToString();
reg.mobile = txtMobile.Text.ToString();
reg.Password = txtPassword.Text.ToString();
reg.ConfirmPassword = txtConfirmPassword.ToString();
reg.age = txtAge.Text.ToString();
if (!isValid)
{
32
foreach (var validationResult in results)
{
Response.Write(validationResult.ErrorMessage.ToString());
}
return;
}
}
Output:
33
PROGRAM 20.
Display the data from the table in a Repeater control using dataset in ASP.net.
Program:-
NULL,
) ON [PRIMARY];
34
<td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td valign="top">Enter Comments:</td>
<td><asp:TextBox ID="txtComment" runat="server" Rows="5" Columns="20"
TextMode="MultiLine"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_click" /></td>
</tr>
</table>
</div>
<div>
<asp:Repeater ID="RepterDetails" runat="server">
<HeaderTemplate>
<table style="border:1px solid #0000FF; width:500px" cellpadding="0">
<tr style="background-color:#FF6600; color:#000000; font-size: large; font-weight:
bold;">
<td colspan="2">
<b>Comments</b>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#EBEFF0">
<td>
<table style="background-color:#EBEFF0; border-top:1px dotted #df5015;
width:500px">
<tr>
<td>
35
Subject:
<asp:Label ID="lblSubject" runat="server" Text='<%# Eval("Subject") %>'
Font-Bold="true" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblComment" runat="server" Text='<%# Eval("CommentOn") %>'
/>
</td>
</tr>
<tr>
<td>
<table style="background-color:#EBEFF0; border-top:1px dotted #df5015; border-
bottom:1px solid #df5015; width:500px">
<tr>
<td>Post By: <asp:Label ID="lblUser" runat="server" Font-Bold="true"
Text='<%# Eval("UserName") %>' /></td>
<td>Created Date: <asp:Label ID="lblDate" runat="server" Font-Bold="true"
Text='<%# Eval("Post_Date") %>' /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
36
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
37
{
con.Open();
cmd = new SqlCommand("INSERT INTO Comment (UserName, Subject, CommentOn,
Post_Date) VALUES (@userName, @subject, @comment, @date)", con);
cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value =
txtName.Text.ToString();
cmd.Parameters.Add("@subject", SqlDbType.NVarChar).Value =
txtSubject.Text.ToString();
cmd.Parameters.Add("@comment", SqlDbType.NVarChar).Value =
txtComment.Text.ToString();
cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now.Date;
cmd.ExecuteNonQuery();
con.Close();
txtName.Text = string.Empty;
txtSubject.Text = string.Empty;
txtComment.Text = string.Empty;
RepeterData();
}
catch (Exception ex)
{
txtComment.Text = ex.Message;
}
}
public void RepeterData()
{
con.Open();
cmd = new SqlCommand("SELECT * FROM Comment ORDER BY Post_Date DESC", con);
DataSet ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
RepterDetails.DataSource = ds;
RepterDetails.DataBind();
38
}
}
Output:
39