PRACTICAL NO.
01
Write the Program the following
a. Create an application to Floyd’s triangle till n rows in C#.
Input:-
using System;
class Program
{
static void Main()
{
Console.Write("Enter the number of rows for Floyd's Triangle: ");
int n = int.Parse(Console.ReadLine());
GenerateFloydsTriangle(n);
}
static void GenerateFloydsTriangle(int n)
{
int number = 1; // Start with the first natural number
for (int i = 1; i <= n; i++) // Loop through each row
{
// Print leading spaces for alignment
for (int j = 1; j <= n - i; j++)
{
Console.Write(" ");
}
// Print numbers in the current row
for (int j = 1; j <= i; j++)
{
Console.Write(number + " ");
number++; // Increment the number for the next position
}
Console.WriteLine(); // Move to the next line after each row
}
}
}
1
b. Create an application to demonstrate on following operation i. Generate Fabinocci
series ii. Test for prime number.
Input:-
using System;
class Program
{
static void Main()
{
Console.WriteLine("Choose an operation:");
Console.WriteLine("1. Generate Fibonacci Series");
Console.WriteLine("2. Test for Prime Number");
Console.Write("Enter your choice (1 or 2): ");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.Write("Enter the number of terms for Fibonacci series: ");
int n = int.Parse(Console.ReadLine());
GenerateFibonacci(n);
break;
case 2:
Console.Write("Enter a number to test for primality: ");
int number = int.Parse(Console.ReadLine());
bool isPrime = IsPrime(number);
Console.WriteLine($"{number} is {(isPrime ? "a prime number" : "not a
prime number")}");
break;
default:
Console.WriteLine("Invalid choice. Please select 1 or 2.");
break;
}
}
static void GenerateFibonacci(int n)
{
int a = 0, b = 1, c;
Console.WriteLine("Fibonacci Series:");
for (int i = 0; i < n; i++)
{
2
Console.Write(a + " ");
c = a + b; // Calculate the next term
a = b; // Update a to the next term
b = c; // Update b to the next term
}
Console.WriteLine(); // New line after the series
}
static bool IsPrime(int number)
{
if (number <= 1) return false; // 0 and 1 are not prime numbers
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0) return false; // Found a divisor, not prime
}
return true; // No divisors found, it's prime
}
}
*******************************OUTPUT*********************************
3
4
PRACTICAL NO. 02
Write the Program the following
a. Create a simple application to demonstrate the concepts boxing and unboxing.
Input:-
using System;
class Program
{
static void Main()
{
// Boxing
int number = 42; // Value type
object boxedNumber = number; // Boxing
Console.WriteLine("Boxed Number: " + boxedNumber);
// Unboxing
int unboxedNumber = (int)boxedNumber; // Unboxing
Console.WriteLine("Unboxed Number: " + unboxedNumber);
// Demonstrating boxing with a method
Console.WriteLine("Demonstrating boxing with a method:");
DisplayBoxedValue(number);
}
static void DisplayBoxedValue(object obj)
{
// This method accepts an object, demonstrating that a value type can be boxed
Console.WriteLine("Value inside the box: " + obj);
}
}
b. Create a simple application to demonstrate use of the concepts of interfaces.
using System;
// Define an interface
interface IPrintable
{
void Print();
}
5
// Define a class that implements the IPrintable interface
class Document : IPrintable
{
public string Content { get; set; }
public Document(string content)
{
Content = content;
}
// Implement the Print method
public void Print()
{
Console.WriteLine("Printing document:");
Console.WriteLine(Content);
}
}
// Define another class that implements the IPrintable interface
class Image : IPrintable
{
public string FileName { get; set; }
public Image(string fileName)
{
FileName = fileName;
}
// Implement the Print method
public void Print()
{
Console.WriteLine("Printing image:");
Console.WriteLine(FileName);
}
}
class Program
{
static void Main()
{
// Create instances of classes that implement the IPrintable interface
Document document = new Document("This is a document.");
Image image = new Image("image.jpg");
// Call the Print method on each instance
document.Print();
6
image.Print();
// Use the interface as a type
IPrintable printableDocument = document;
IPrintable printableImage = image;
// Call the Print method using the interface type
printableDocument.Print();
printableImage.Print();
}
}
*******************************OUTPUT*********************************
7
PRACTICAL NO. 03
Write the Program the following
a. Create a simple web page with various server controls to demonstrate setting and use
of their properties. (Example: AutoPostBack)
Input:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Server Controls Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Server Controls Demo</h2>
<asp:Label ID="Label1" runat="server" Text="Select a color:"></asp:Label>
<asp:DropDownList ID="ColorDropDown" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ColorDropDown_SelectedIndexChanged">
<asp:ListItem Text="Select a color" Value="" />
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Blue" Value="Blue" />
</asp:DropDownList>
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Selected Color: "></asp:Label>
<asp:Label ID="SelectedColorLabel" runat="server" Text=""></asp:Label>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Click Me"
OnClick="Button1_Click" />
<asp:Label ID="ResultLabel" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
8
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This method is called when the page is loaded
}
protected void ColorDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
// Update the label with the selected color
SelectedColorLabel.Text = ColorDropDown.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
// Display a message when the button is clicked
ResultLabel.Text = "Button clicked!";
}
}
}
b. Demonstrate the use of Treeview operations on the web form.
Input:-
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This method is called when the page is loaded
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
// Update the label with the selected node
SelectedNodeLabel.Text = "Selected Node: " +
TreeView1.SelectedNode.Text;
}
protected void AddNodeButton_Click(object sender, EventArgs e)
9
{
// Add a new node to the TreeView
TreeNode newNode = new TreeNode("New Node");
TreeView1.Nodes[0].ChildNodes.Add(newNode);
}
protected void RemoveNodeButton_Click(object sender, EventArgs e)
{
// Remove the last child node from the TreeView
if (TreeView1.Nodes[0].ChildNodes.Count > 0)
{
TreeView1.Nodes[0].ChildNodes.RemoveAt(TreeView1.Nodes[0].ChildNodes.Count
- 1);
}
}
protected void ExpandNodeButton_Click(object sender, EventArgs e)
{
// Expand the first node in the TreeView
TreeView1.Nodes[0].Expand();
}
protected void CollapseNodeButton_Click(object sender, EventArgs e)
{
// Collapse the first node in the TreeView
TreeView1.Nodes[0].Collapse();
}
}
}
*******************************OUTPUT*********************************
10
11
12
PRACTICAL NO. 04
Write the Program the following
a.Create a Registration form to demonstrate use of various Validation controls.
b.Create Web Form to demonstrate use of Adrotator Control.
Code 1:-
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Registration Form</h2>
<asp:Label ID="NameLabel" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="NameValidator" runat="server"
ControlToValidate="NameTextBox"
ErrorMessage="Name is required." ForeColor="Red" />
<br /><br />
<asp:Label ID="EmailLabel" runat="server" Text="Email:"></asp:Label>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailValidator" runat="server"
ControlToValidate="EmailTextBox"
ErrorMessage="Email is required." ForeColor="Red" />
<asp:RegularExpressionValidator ID="EmailRegexValidator" runat="server"
ControlToValidate="EmailTextBox"
ErrorMessage="Invalid email format." ForeColor="Red"
ValidationExpression="^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" />
13
<br /><br />
<asp:Label ID="PasswordLabel" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="PasswordTextBox" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordValidator" runat="server"
ControlToValidate="PasswordTextBox"
ErrorMessage="Password is required." ForeColor="Red" />
<br /><br />
<asp:Label ID="ConfirmPasswordLabel" runat="server" Text="Confirm
Password:"></asp:Label>
<asp:TextBox ID="ConfirmPasswordTextBox" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordValidator" runat="server"
ControlToValidate="ConfirmPasswordTextBox"
ErrorMessage="Confirm Password is required." ForeColor="Red" />
<asp:CompareValidator ID="PasswordCompareValidator" runat="server"
ControlToCompare="PasswordTextBox"
ControlToValidate="ConfirmPasswordTextBox" ErrorMessage="Passwords do
not match." ForeColor="Red" />
<br /><br />
<asp:Button ID="RegisterButton" runat="server" Text="Register"
OnClick="RegisterButton_Click" />
<asp:Label ID="ResultLabel" runat="server" Text=""
ForeColor="Green"></asp:Label>
</div>
</form>
</body>
</html>
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This method is called when the page is loaded
}
protected void RegisterButton_Click(object sender, EventArgs e)
{
14
// Check if the page is valid
if (Page.IsValid)
{
// Registration logic here (e.g., save to database)
ResultLabel.Text = "Registration successful!";
}
}
}
}
Code 2:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AdRotator Control Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>AdRotator Control Demo</h2>
<asp:AdRotator ID="AdRotator1" runat="server"
AdvertisementFile="~/Advertisements.xml"
Target="_blank" />
</div>
</form>
</body>
</html>
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>~/Images/Ad1.jpg</ImageUrl>
<NavigateUrl>https://www.example.com/ad1</NavigateUrl>
<AlternateText>Ad 1</AlternateText>
<Impressions>50</Impressions>
</Ad>
<Ad>
<ImageUrl>~/Images/Ad2.jpg</ImageUrl>
<NavigateUrl>https://www.example.com/ad2</NavigateUrl>
<AlternateText>Ad 2</AlternateText>
<Impressions>30</Impressions>
</Ad>
15
<Ad>
<ImageUrl>~/Images/Ad3.jpg</ImageUrl>
<NavigateUrl>https://www.example.com/ad3</NavigateUrl>
<AlternateText>Ad 3</AlternateText>
<Impressions>20</Impressions>
</Ad>
</Advertisements>
*******************************OUTPUT*********************************
16
PRACTICAL NO. 05
Write the Program the following
a. Create Web Form to demonstrate use of Website Navigation controls
b. Create a web application to demonstrate various states of ASP.NET Pages.
Code:-1
Site map
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode url="Default.aspx" title="Home" >
<siteMapNode url="Page1.aspx" title="Page 1" />
<siteMapNode url="Page2.aspx" title="Page 2" />
<siteMapNode url="Page3.aspx" title="Page 3" />
</siteMapNode>
</siteMap>
Web form code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI.WebControls"
Assembly="System.Web.Extensions" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Website Navigation Controls Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Website Navigation Controls Demo</h2>
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"
Orientation="Horizontal" />
<br /><br />
<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="SiteMapDataSource1" />
<br /><br />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
ShowStartingNode="false" />
</div>
</form>
17
</body>
</html>
Code 2:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET Page States Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>ASP.NET Page States Demo</h2>
<asp:Label ID="Label1" runat="server" Text="Page Load Count: 0"></asp:Label>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Click Me"
OnClick="Button1_Click" />
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Session Value: "></asp:Label>
<br /><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Save to Session"
OnClick="Button2_Click" />
</div>
</form>
</body>
</html>
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
private int pageLoadCount;
protected void Page_Load(object sender, EventArgs e)
{
// Check if the page is being loaded for the first time or is a postback
if (!IsPostBack)
{
18
// Initialize the page load count
pageLoadCount = 0;
Label1.Text = "Page Load Count: " + pageLoadCount;
}
else
{
// Increment the page load count on postback
pageLoadCount++;
Label1.Text = "Page Load Count: " + pageLoadCount;
}
// Display the session value if it exists
if (Session["SavedValue"] != null)
{
Label2.Text = "Session Value: " + Session["SavedValue"].ToString();
}
else
{
Label2.Text = "Session Value: Not set";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// This button click demonstrates postback
// Additional logic can be added here
}
protected void Button2_Click(object sender, EventArgs e)
{
// Save the value from the TextBox to the session
Session["SavedValue"] = TextBox1.Text;
Label2.Text = "Session Value: " + Session["SavedValue"].ToString();
}
}
}
*******************************OUTPUT*********************************
19
20
PRACTICAL NO. 06
Write the Program the following
a. Create a web application for inserting and deleting records from a database.
b. Create a web application to display Using Disconnected Data Access and Databinding
using GridView.
Code1:-
using System;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
private string connectionString = "Data Source=YourServerName;Initial
Catalog=MyDatabase;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Insert record into database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Employees (Name, Email) VALUES (@Name,
@Email)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", TextBox1.Text);
command.Parameters.AddWithValue("@Email", TextBox2.Text);
command.ExecuteNonQuery();
}
// Clear text boxes
TextBox1.Text = string.Empty;
21
TextBox2.Text = string.Empty;
// Rebind GridView
BindGridView();
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
// Delete record from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "DELETE FROM Employees WHERE EmployeeID =
@EmployeeID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@EmployeeID", e.CommandArgument);
command.ExecuteNonQuery();
}
// Rebind GridView
BindGridView();
}
private void BindGridView()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Employees";
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
}
}
}
Code2 :- using System;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
22
{
private string connectionString = "Data Source=YourServerName;Initial
Catalog=MyDatabase;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Insert record into database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Employees (Name, Email) VALUES (@Name,
@Email)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", TextBox1.Text);
command.Parameters.AddWithValue("@Email", TextBox2.Text);
command.ExecuteNonQuery();
}
// Clear text boxes
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
// Rebind GridView
BindGridView();
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
// Delete record from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "DELETE FROM Employees WHERE EmployeeID =
@EmployeeID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@EmployeeID", e.CommandArgument);
command.ExecuteNonQuery();
}
23
// Rebind GridView
BindGridView();
}
private void BindGridView()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT
*******************************OUTPUT*********************************
24
25
PRACTICAL NO. 07
Write the Program the following
a. Create a web application to demonstrate the use of different types of Cookies.
b. Create a web application to demonstrate Form Security and Windows Security with
proper Authentication and Authorization properties.
Code 1:-
using System;
using System.Web;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// Set a session cookie
HttpCookie sessionCookie = new HttpCookie("SessionCookie");
sessionCookie["Name"] = TextBox1.Text;
sessionCookie.Expires = DateTime.Now.AddMinutes(20); // Session cookies expire
when the browser is closed
Response.Cookies.Add(sessionCookie);
Label3.Text = "Session cookie set for Name: " + TextBox1.Text;
}
protected void Button2_Click(object sender, EventArgs e)
{
// Set a persistent cookie
HttpCookie persistentCookie = new HttpCookie("PersistentCookie");
persistentCookie["Email"] = TextBox2.Text;
persistentCookie.Expires = DateTime.Now.AddDays(30); // Persistent cookies expire
after 30 days
Response.Cookies.Add(persistentCookie);
Label3.Text = "Persistent cookie set for Email: " + TextBox2.Text;
}
protected void Button3_Click(object sender, EventArgs e)
{
26
// Retrieve cookies
string sessionName = Request.Cookies["SessionCookie"]?["Name"] ?? "Not set";
string persistentEmail = Request.Cookies["PersistentCookie"]?["Email"] ?? "Not
set";
Label3.Text = $"Session Cookie Name: {sessionName}, Persistent Cookie Email:
{persistentEmail}";
}
}
}
Code 2:-
using System;
using System.Web;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// Set a session cookie
HttpCookie sessionCookie = new HttpCookie("SessionCookie");
sessionCookie["Name"] = TextBox1.Text;
sessionCookie.Expires = DateTime.Now.AddMinutes(20); // Session cookies expire
when the browser is closed
Response.Cookies.Add(sessionCookie);
Label3.Text = "Session cookie set for Name: " + TextBox1.Text;
}
protected void Button2_Click(object sender, EventArgs e)
{
// Set a persistent cookie
HttpCookie persistentCookie = new HttpCookie("PersistentCookie");
persistentCookie["Email"] = TextBox2.Text;
persistentCookie.Expires = DateTime.Now.AddDays(30); // Persistent cookies expire
after 30 days
Response.Cookies.Add(persistentCookie);
Label3.Text = "Persistent cookie set for Email: " + TextBox2.Text;
}
protected void Button3_Click(object sender, EventArgs e)
{
// Retrieve cookies
27
string sessionName = Request.Cookies["SessionCookie"]?["Name"] ?? "Not set";
string persistentEmail = Request.Cookies["PersistentCookie"]?["Email"] ?? "Not
set";
Label3.Text = $"Session Cookie Name: {sessionName}, Persistent Cookie Email:
{persistentEmail}";
}
}
}
*******************************OUTPUT*********************************
28
PRACTICAL NO. 08
Write the Program the following
a. Create a web application for inserting and deleting records from a database. (Using
Execute Non Query).
b. Create a web application for user defined exception handling
Code 1:-
using System;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
private string connectionString = "Data Source=YourServerName;Initial
Catalog=MyDatabase;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Insert record into database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Employees (Name, Email) VALUES (@Name,
@Email)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", TextBox1.Text);
command.Parameters.AddWithValue("@Email", TextBox2.Text);
command.ExecuteNonQuery(); // Execute the insert command
}
// Clear text boxes
TextBox1.Text = string.Empty;
29
TextBox2.Text = string.Empty;
// Rebind GridView
BindGridView();
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
// Delete record from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "DELETE FROM Employees WHERE EmployeeID =
@EmployeeID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@EmployeeID", e.CommandArgument);
command.ExecuteNonQuery(); // Execute the delete command
}
// Rebind GridView
BindGridView();
}
private void BindGridView()
{
using (Sql
Code2:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>User Defined Exception Handling</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>User Defined Exception Handling</h2>
<asp:Label ID="Label1" runat="server" Text="Enter a number
(1-100):"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br /><br />
30
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"
/>
<br /><br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
using System;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int number = int.Parse(TextBox1.Text);
ValidateNumber(number);
Label2.Text = "You entered a valid number: " + number;
}
catch (CustomException ex)
{
Label2.Text = "Error: " + ex.Message;
}
catch (FormatException)
{
Label2.Text = "Error: Please enter a valid integer.";
}
catch (Exception ex)
{
Label2.Text = "An unexpected error occurred: " + ex.Message;
}
}
private void ValidateNumber(int number)
{
if (number < 1 || number > 100)
{
31
throw new CustomException("The number must be between 1 and 100.");
}
}
}
}
*******************************OUTPUT*********************************
32
33
PRACTICAL NO. 09
Write the program for the following:
a. Create a web application to demonstrate use of GridView button column and
GridView event along with paging and sorting.
b. Create a web application to demonstrate data binding using Details View and
FormView Control
Code 1:-
Webform code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GridView Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Employee List</h2>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"
PageSize="2" OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
SortExpression="EmployeeID" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email"
SortExpression="Email" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="EditButton" runat="server" Text="Edit"
CommandArgument='<%# Eval("EmployeeID") %>' OnClick="EditButton_Click" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete"
CommandArgument='<%# Eval("EmployeeID") %>'
OnClick="DeleteButton_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
34
</asp:GridView>
</div>
</form>
</body>
</html>
File
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
private string connectionString = "Data Source=YourServerName;Initial
Catalog=MyDatabase;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Employees", connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
35
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GetEmployeeData();
if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " +
GetSortDirection(e.SortExpression);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// Toggle sort direction
string sortDirection = "ASC";
string previousColumn = ViewState["SortColumn"] as string;
if (previousColumn
Code 2:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DetailsView and FormView Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Employee Details</h2>
<asp:DetailsView ID="DetailsView1" runat="server"
AutoGenerateRows="false" DataKeyNames="EmployeeID"
OnModeChanging="DetailsView1_ModeChanging">
<Fields>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
ReadOnly="true" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
</Fields>
</asp:DetailsView>
<asp:Button ID="ButtonEdit" runat="server" Text="Edit"
OnClick="ButtonEdit_Click" />
36
<asp:Button ID="ButtonInsert" runat="server" Text="Insert New Employee"
OnClick="ButtonInsert_Click" />
<br /><br />
<h2>Insert New Employee</h2>
<asp:FormView ID="FormView1" runat="server"
DataKeyNames="EmployeeID" OnItemInserted="FormView1_ItemInserted"
OnItemCommand="FormView1_ItemCommand">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextBoxName" runat="server" Text='<%#
Bind("Name") %>'></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Email:"></asp:Label>
<asp:TextBox ID="TextBoxEmail" runat="server" Text='<%#
Bind("Email") %>'></asp:TextBox>
<br />
<asp:Button ID="ButtonInsert" runat="server" CommandName="Insert"
Text="Insert" />
</ItemTemplate>
<InsertItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Email:"></asp:Label>
<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<br />
<asp:Button ID="ButtonInsert" runat="server" CommandName="Insert"
Text="Insert" />
</InsertItemTemplate>
</asp:FormView>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
37
private string connectionString = "Data Source=YourServerName;Initial
Catalog=MyDatabase;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
*******************************OUTPUT*********************************
38
PRACTICAL NO. 10
Write the program for the following:
a. Create a web application to demonstrate JS Bootstrap Button.
b. Create a web application to demonstrate use of various Ajax controls
Code1:-
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Button Styles</h2>
<button type="button" class="btn">Basic</button>
<button type="button" class="btn btn-default">Default</button>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-link">Link</button>
</div>
</body>
</html>
Code2:-
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
39
<head runat="server">
<title>AJAX Controls Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></
script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div class="container">
<h2>AJAX Controls Demo</h2>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Current Time:
"></asp:Label>
<asp:Label ID="LabelTime" runat="server"></asp:Label>
<br />
<asp:Button ID="ButtonGetTime" runat="server" Text="Get Current
Time" OnClick="ButtonGetTime_Click" />
<br /><br />
<asp:Timer ID="Timer1" runat="server" Interval="5000"
OnTick="Timer1_Tick" />
<asp:Label ID="LabelTimer" runat="server" Text="Timer is
running..."></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
using System;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LabelTime.Text = DateTime.Now.ToString("T");
}
}
protected void ButtonGetTime_Click(object sender, EventArgs e)
40
{
LabelTime.Text = DateTime.Now.ToString("T");
}
protected void Timer1_Tick(object sender, EventArgs e)
{
LabelTime.Text = DateTime.Now.ToString("T");
}
}
}
*******************************OUTPUT*********************************
41