0% found this document useful (0 votes)
12 views54 pages

C# Vinay Practical File.

The document contains multiple C# programming examples, each demonstrating different programming concepts such as generating prime numbers, checking for Armstrong numbers, sorting arrays, and implementing abstract and sealed classes. It also covers advanced topics like exception handling, method overloading, method overriding, and the use of delegates, interfaces, and indexers. Additionally, there is a program for creating a basic calculator using Windows Forms.

Uploaded by

ourkillerboy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views54 pages

C# Vinay Practical File.

The document contains multiple C# programming examples, each demonstrating different programming concepts such as generating prime numbers, checking for Armstrong numbers, sorting arrays, and implementing abstract and sealed classes. It also covers advanced topics like exception handling, method overloading, method overriding, and the use of delegates, interfaces, and indexers. Additionally, there is a program for creating a basic calculator using Windows Forms.

Uploaded by

ourkillerboy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

PROGRAM 1.

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.

Write a program to print ARMSTRONG number.


Program:- using System;
namespace Armstrong_number
{
class Program
{
public static void main(string[] args)
{
int i = 0;
int digitCount = 0;
int[] digitArray = new int[10];
double sum = 0;
Console.Write("Enter the Number : ");
int number = int.Parse(Console.ReadLine());
int temporaryNumber = number;
while (number > 0)
{
digitArray[i++] = number % 10;
number = number / 10; digitCount+
+;
}
for (i = 0; i < digitCount; i++)
{
sum += Math.Pow(digitArray[i], digitCount);
}
if (sum == temporaryNumber)
{
Console.WriteLine($"The Number {temporaryNumber} is Armstrong");
}
else
{
Console.WriteLine($"The Number {temporaryNumber} is not Armstrong");
}
Console.ReadLine();
}
}
}

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:");

for (int i = 0; i < 10; i++)


{
while (!int.TryParse(Console.ReadLine(), out numbers[i]))
{
Console.WriteLine("Invalid input. Please enter an integer.");
}
}

Array.Sort(numbers);

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


foreach (int number in numbers)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
}

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();
}
}
}

public abstract class A


{
public abstract void show();
}
public sealed class B : A
{
public override void show()
{
Console.WriteLine("I am sealed class method.");
}
}

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 };

Console.WriteLine("Jagged Array Elements:");


int row = 0;
foreach (int[] innerArray in member)
{
Console.Write($"Row {row}: ");
foreach (int item in innerArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
row++;
}
}
}
}

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

Console.WriteLine("Boxed value: " + boxed);

int unboxed = (int)boxed; // Unboxing


Console.WriteLine("Unboxed value: " + unboxed);

// Just to show that it's a separate copy


number = 100;
Console.WriteLine("Original number changed to: " +
number);
Console.WriteLine("Boxed value remains: " +
boxed);
}
}

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());

Console.WriteLine("Enter the second number:");


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

int result = num1 / num2;


Console.WriteLine($"Result: {num1} / {num2} = {result}");
}
catch (DivideByZeroException)
{
Console.WriteLine("Error: Division by zero is not allowed.");
}
catch (FormatException)
{
Console.WriteLine("Error: Please enter valid numeric values.");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed.");
}
}
}

17
Output:

18
PROGRAM 10.
Write a program to implement multiple inheritances using interface.
Program:- using System;

// Define the first interface


public interface IFlyable
{
void Fly();
}

// Define the second interface


public interface ISwimmable
{
void Swim();
}

// Define the third interface


public interface IWalkable
{
void Walk();
}

// A class that implements all three interfaces


// This class 'inherits' the contracts from IFlyable, ISwimmable, and IWalkable
public class Duck : IFlyable, ISwimmable, IWalkable
{
// The class MUST provide implementations for ALL methods declared in ALL implemented interfaces

public void Fly()


{
Console.WriteLine("Duck is flying!");
}

public void Swim()


{
Console.WriteLine("Duck is swimming!");
}

public void Walk()


{
Console.WriteLine("Duck is walking!");
}

// The class can also have its own unique members


public void Quack()
{
Console.WriteLine("Quack! Quack!");
}
}

public class Program


{
public static void Main(string[] args)
19
{
Console.WriteLine("--- Demonstrating Multiple Inheritance using Interfaces ---");

// Create an instance of the Duck class


Duck myDuck = new Duck();

Console.WriteLine("\nUsing the Duck object directly:");


myDuck.Quack(); // Duck's specific method
myDuck.Fly(); // Implemented from IFlyable
myDuck.Swim(); // Implemented from ISwimmable
myDuck.Walk(); // Implemented from IWalkable

Console.WriteLine("\nUsing interface references (Polymorphism):");

// The same Duck object can be treated as an IFlyable


IFlyable flyableAnimal = myDuck;
// flyableAnimal.Swim(); // ERROR: IFlyable reference only knows about Fly()
flyableAnimal.Fly();

// The same Duck object can be treated as an ISwimmable


ISwimmable swimmableAnimal = myDuck;
swimmableAnimal.Swim();

// The same Duck object can be treated as an IWalkable


IWalkable walkableAnimal = myDuck;
walkableAnimal.Walk();

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;
}

public static double Subtract(double a, double b)


{
return a - b;
}

public static double Multiply(double a, double b)


{
return a * b;
}

public static double Divide(double a, double b)


{
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
return a / b;
}

static void Main(string[] args)


{
// Create instances of the delegate for each operation
ArithmeticOperation add = Add;
ArithmeticOperation subtract = Subtract;
ArithmeticOperation multiply = Multiply;
ArithmeticOperation divide = Divide;

// Example usage
double num1 = 10;
double num2 = 5;

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


Console.WriteLine($"Subtraction: {num1} - {num2} = {subtract(num1, num2)}");
Console.WriteLine($"Multiplication: {num1} * {num2} = {multiply(num1, num2)}");
Console.WriteLine($"Division: {num1} / {num2} = {divide(num1, num2)}");
22
// Wait for user input before closing
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}

23
Output:

24
PROGRAM 12:
Write a program to implement Indexer
Program:- using System;

public class SampleCollection


{
// Backing store for the indexer
private string[] elements = new string[10];

// 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

collection = new SampleCollection();

// Setting values using the indexer


collection[0] = "Hello";
collection[1] = "World";
collection[2] = "Indexer";
collection[3] = "Example";

25
// Getting values using the indexer
for (int i = 0; i < 4; i++)
{
Console.WriteLine(collection[i]);
}

// Uncommenting the following line will throw an exception


// Console.WriteLine(collection[10]);
}
}

Output:

26
PROGRAM 13.
Write a program to implement method overloading.

Program:- using System;

class Program
{
// Method to add two integers
public static int Add(int a, int b)
{
return a + b;
}

// Method to add three integers


public static int Add(int a, int b, int c)
{
return a + b + c;
}

// Method to add two double values


public static double Add(double a, double b)
{
return a + b;
}

// Method to add two strings (concatenation)


public static string Add(string a, string b)
{
return a + b;
}

static void Main(string[] args)


{
// Calling the overloaded methods
int sum1 = Add(5, 10);
int sum2 = Add(5, 10, 15);
double sum3 = Add(5.5, 10.5);
string concatenated = Add("Hello, ", "World!");

// Displaying the results


Console.WriteLine("Sum of two integers: " + sum1);
Console.WriteLine("Sum of three integers: " + sum2);
Console.WriteLine("Sum of two doubles: " + sum3);
Console.WriteLine("Concatenated strings: " + concatenated);
}
}

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.");
}
}

// Another derived class


class Cat : Animal
{
// Overriding the Speak method
public override void Speak()
{
Console.WriteLine("The cat meows.");
}
}

class Program
{
static void Main(string[] args)
{
// Creating instances of the derived classes
Animal myDog = new Dog();
Animal myCat = new Cat();

// Calling the Speak method


myDog.Speak(); // Output: The dog barks.
myCat.Speak(); // Output: The cat meows.
// You can also call the base class method
Animal myAnimal = new Animal();
myAnimal.Speak(); // Output: The animal makes a sound.
}
}
}
29
Output:

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();
}

private void button_Click(object sender, EventArgs e)


{
if ((textBoxResult.Text == "0") || (isOperationPerformed))
textBoxResult.Clear();

isOperationPerformed = false;
Button button = (Button)sender;
textBoxResult.Text += button.Text;
}

private void buttonClear_Click(object sender, EventArgs e)


{
textBoxResult.Text = "0";
resultValue = 0;
}

private void buttonOperation_Click(object sender, EventArgs e)


{
Button button = (Button)sender;
operation = button.Text;
resultValue = double.Parse(textBoxResult.Text);
isOperationPerformed = true;
}

private void buttonEquals_Click(object sender, EventArgs e)


{
switch (operation)
{

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:-

STEP 1:- Database Setup: - SQL Script to Create Employee Table

CREATE DATABASE EmployeeDB;


GO
USE EmployeeDB;
GO
CREATE TABLE Employees
( EmpId INT PRIMARY
KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Gender NVARCHAR(10),
ContactNo NVARCHAR(15),
Designation NVARCHAR(50),
Address NVARCHAR(255),
Pin NVARCHAR(10)
);
STEP 2:- Windows Forms UI Design (WinForms)

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.

STEP 3:- C# Code (Backend)


18
19
using System;
using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;
namespace Employees
{
public partial class MainForm : Form
{
private SQLiteConnection connection;
public MainForm()
{
InitializeComponent();
InitializeDatabase();
LoadEmployees();
}
private void InitializeDatabase()
{
connection = new SQLiteConnection("Data Source=employee.db;Version=3;");
connection.Open();
}
private void LoadEmployees()
{
string query = "SELECT * FROM employees";
SQLiteDataAdapter adapter = new SQLiteDataAdapter(query, connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridViewEmployees.DataSource = dataTable;
}
private void buttonAdd_Click(object sender, EventArgs e)
{
string query = "INSERT INTO employees (EmpId, FirstName, LastName, Gender,
ContactNo, Designation, Address, Pin) VALUES (@EmpId, @FirstName, @LastName, @Gender,
@ContactNo, @Designation, @Address, @Pin)";
using (SQLiteCommand command = new SQLiteCommand(query, connection))
{

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:-

STEP 1:- Create SQL Server Database (MyDb)

CREATE DATABASE MyDb;

GO

USE MyDb;

GO

CREATE TABLE Employees (

Id INT PRIMARY KEY IDENTITY,

FName VARCHAR(100),

LName VARCHAR(100),

Department VARCHAR(100),

);

INSERT INTO Employees (Name, Position) VALUES

('Alice’, ‘Brown', 'HR'),

('Bob’, ‘Smith', 'IT');

('Carol’, ‘Jones', 'Finance');

OR

23
Step 2: Create a Windows Forms Application (C#)

1. Open Visual Studio

2. Create a new Windows Forms App (.NET Framework) project

3. Add these controls in the Form Designer:

o ListBox – listBoxName

o ListBox – listBoxPosition

o Button – btnLoad (Text: "Load Data")

Step 3: Write the Code to Connect to the Database

using System;

using System.Data.SqlClient;

using System.IO;

using System.Windows.Forms;

namespace MyDB

private void btnLoadData_Click(object sender, EventArgs e)

string connectionString =
"Server=YOUR_SERVER_NAME;Database=MyDb;Trusted_Connection=True;";

using (SqlConnection connection = new SqlConnection(connectionString))

connection.Open();

string query = "SELECT FirstName, LastName FROM Employee";

SqlCommand command = new SqlCommand(query, connection);

SqlDataReader reader = command.ExecuteReader();

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:-

Step 1: Make a database with a table in SQL Server.

CREATE DATABASE MyDb;

GO

USE MyDb;

GO

CREATE TABLE Students (

StudentId INT PRIMARY KEY IDENTITY,

StudentName VARCHAR(100),

Branch VARCHAR(50),

MobileNo VARCHAR (20)

);

INSERT INTO Students (StudentName, Branch, MobileNo) VALUES

(‘1’, 'Glen', 'CS', '32569874'),

(‘2’, ‘Devid’, 'ME', '325698214'),

(‘3’, 'OM', 'CS', '0213654');

(‘4’, ‘Polad', 'ME', '0011254589');

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

private void Form1_Load(object sender,

EventArgs e) {

SqlDataAdapter da = new

SqlDataAdapter("SELECT FROM Student",

"server = MCNDESKTOP33; database =

Avinash; UID = sa; password = ******");

DataSet ds = new DataSet();

da.Fill(ds, "Student");

dataGridView1.DataSource =

ds.Tables["Student"].DefaultView;

Step 3: Code for the Save and Reset button

using System;

using System.Data;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace WindowsFormsDataGrid

public partial class Form1: Form

{ public Form1() {

InitializeComponent();

private void Form1_Load(object sender, EventArgs e) {

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", "server = MCNDES


KTOP33; database = Avinash; UID = sa; password = *******");

DataSet ds = new DataSet();

da.Fill(ds, "Student");
27
dataGridView1.DataSource = ds.Tables["Student"].DefaultView;

private void button1_Click(object sender, EventArgs e) {

SqlConnection con = new SqlConnection("server = MCNDESKTOP33; database = Avinash;


UID = sa; password = *******");

con.Open();

string qur = "INSERT INTO Student VALUES ('" + textBox1.Text + "','" + textBox2.Text +
"','" + textBox3.Text + "','" + textBox4.Text + "')";

SqlCommand cmd = new SqlCommand(qur, con);

cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("Inserted sucessfully");

textBox1.Text = "";

textBox2.Text = "";

textBox3.Text = "";

textBox4.Text = "";

private void button2_Click(object sender, EventArgs e)

{ 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:-

ASP.NET Registration Form (ASPX Page)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs"


Inherits="YourNamespace.Register" %>

<!DOCTYPE html>

<html>

<head>

<title>Registration Form</title>

</head>

<body>

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


<div>
Full Name :<asp:TextBox ID="txtName" placeholder="Enter Full Name"
runat="server"></asp:TextBox>

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


ErrorMessage="Name cannot be blank" ControlToValidate="txtName"
ForeColor="Red"></asp:RequiredFieldValidator>

<br />
Email :<asp:TextBox ID="txtEmail" placeholder="Enter Email"
runat="server"></asp:TextBox>

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


ErrorMessage="Email cannot be blank" ControlToValidate="txtEmail"
ForeColor="Red"></asp:RequiredFieldValidator>

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


ControlToValidate="txtEmail" ErrorMessage="Enter proper email format" ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></
asp:RegularExpressionValidator>

<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 />

<asp:Button ID="btnSubmit" runat="server" Text="Submit"


OnClick="btnSubmit_Click" />
</div>
</form>

</body>

</html>

Code-Behind: Register.aspx.cs

public class register


{
[Required(ErrorMessage = "Name is required")]
public string name
{
get;
set;
}

[Required(ErrorMessage = "email is required")]


[RegularExpression(@ "\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:
[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
ErrorMessage = "Please enter proper email")]
public string email
{
get;
set;
}

31
[Required(ErrorMessage = "Mobile is required")]
[RegularExpression(@ "\d{10}", ErrorMessage = "Please enter 10 digit Mobile No.")]
public string mobile
{
get;
set;
}

[Required(ErrorMessage = "Password is required")]


[DataType(DataType.Password)]
public string Password
{
get;
set;
}

[Required(ErrorMessage = "Confirm Password is required")]


[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword
{
get;
set;
}

[Required(ErrorMessage = "Age is required")]


[Range(typeof(int), "18", "40", ErrorMessage = "Age can only be between 18 and 40")]
public string age
{
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:

protected void btnSubmit_Click(object sender, EventArgs e)


{
register reg = new register();

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();

var context = new ValidationContext(reg, serviceProvider: null, items: null);


var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(reg, context, results, true);

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:-

STEP 1:- Create the Database Table

CREATE TABLE [dbo].[Comment] (

NULL,

[Subject] [nvarchar](max) NULL,

[CommentOn] [nvarchar](max) NULL,

[Post_Date] [datetime] NULL

) ON [PRIMARY];

STEP 2:- Design the Web Form

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Repeter_Control_Example.aspx.cs" Inherits="Repeter_Control_Example" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h3>Repeter Control in ASP.NET</h3>
<div>
<table>
<tr>
<td>Enter Name:</td>
<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Enter Subject:</td>

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>

Step 3: Handle the Button Click Event


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Repeter_Control_Example : System.Web.UI.Page
{
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
SqlConnection con = new SqlConnection("Data Source=.;Initial
Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RepeterData();
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
try

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

You might also like