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

C# Record

The document outlines procedures for creating ASP.NET applications using HTML server controls to collect job seeker details, display submitted data in a table format, and implement email registration with validation techniques. It includes steps for designing web forms, handling form submissions, and validating user inputs. Additionally, it describes creating a Windows Forms application to access and manipulate data from an SQL Server database using a DataGrid control.

Uploaded by

drsaranyarcw
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)
53 views

C# Record

The document outlines procedures for creating ASP.NET applications using HTML server controls to collect job seeker details, display submitted data in a table format, and implement email registration with validation techniques. It includes steps for designing web forms, handling form submissions, and validating user inputs. Additionally, it describes creating a Windows Forms application to access and manipulate data from an SQL Server database using a DataGrid control.

Uploaded by

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

Ex.No 01 Design ASP.

Net web form using Html Server Controls to


22.12.2025 enter job seeker’s detail

Aim:
To create an ASP.NET application using Html Server Controls to enter job seeker’s detail

Procedure:
Step 1: Create a new ASP.NET Web Application (Choose "Empty" template with Web
Forms).
Step 2: Design the Form in the default Default.aspx page to collect data.
A) WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Jobseekerform.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Job Seeker's Detail Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Job Seeker's Detail Form</h2>
<asp:Label ID="lblName" runat="server" Text="Name: "></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br /><br />

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


<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblPhone" runat="server" Text="Phone Number: "></asp:Label>
<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblResume" runat="server" Text="Upload Resume: "></asp:Label>
<asp:FileUpload ID="fileResume" runat="server" />
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>

1
Step 3: Handle Form Submission in the Default.aspx.cs code-behind to process the data
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Jobseekerform
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string email = txtEmail.Text;
string phone = txtPhone.Text;
string resumeFileName = fileResume.FileName;

// Here you can add code to save the details to a database or send an email, etc.
// For now, we'll just display a simple confirmation message.
Response.Write($"<script>alert('Thank you, {name}. Your details have been submitted
successfully!');</script>");
}

2
}
}

Step 4: Save and Run the Project

OUTPUT

3
Ex.No:03 Write an ASP.Net application to retrieve form data and display it the
client browser in a table format

AIM:
To create an ASP.NET application that retrieves form data and displays it in a table format in
the client browser.

PROCEDURE:
1. Create a new ASP.NET Web Application (Choose "Empty" template with Web Forms).
2. Design the Form in the default Default.aspx page to collect data.

Default.aspx Page

4
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>
<html>
<head runat="server">
<title>Form Data Display</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}

table, th, td {
border: 1px solid black;
}

th, td {
padding: 8px;
text-align: left;
}

.form-container {
margin-bottom: 20px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="form-container">
<h2>Enter Your Data</h2>
<label for="txtName">Name:</label>

5
<input type="text" id="txtName" runat="server" /><br />
<label for="txtEmail">Email:</label>
<input type="text" id="txtEmail" runat="server" /><br />
<label for="txtAge">Age:</label>
<input type="number" id="txtAge" runat="server" /><br /><br />
<button type="submit" id="btnSubmit" runat="server"
onserverclick="btnSubmit_Click">Submit</button>
</div>

<h3>Submitted Data</h3>
<asp:GridView ID="gridViewData" runat="server" AutoGenerateColumns="True"
Visible="false" />
</form>
</body>
</html>

6
3. Handle Form Submission in the Default.aspx.cs code-behind to process the data
A) Default.aspx.cs
In the code-behind file, the form data will be processed and stored. Afterward, we will bind
the data to the GridView.
using System;
using System.Collections.Generic;
using System.Web.UI;

namespace WebApplication1
{
public partial class Default : Page
{
// A list to store the data entered in the form
private static List<Person> submittedData = new List<Person>();

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{

7
// Hide the GridView initially until there is data to display
gridViewData.Visible = false;
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
// Retrieve form data
string name = txtName.Value;
string email = txtEmail.Value;
int age = int.Parse(txtAge.Value);

// Store data in the list


submittedData.Add(new Person { Name = name, Email = email, Age = age });

// Bind the data to the GridView


gridViewData.DataSource = submittedData;
gridViewData.DataBind();

// Show the GridView once the data is available


gridViewData.Visible = true;

// Clear the form inputs after submission


txtName.Value = "";
txtEmail.Value = "";
txtAge.Value = "";
}

// Simple class to represent a person


public class Person
{

8
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
}
}
4. Save and Run the Project

Ex.No:03 Apply appropriate validation techniques in E-Mail registration form


using validation controls
9
AIM:
To apply appropriate validation techniques in an email registration form using validation
controls, you can use a combination of standard validation controls in ASP.NET. These validation
controls ensure that the user inputs are correct and meet the required criteria before the form is
submitted.

PROCEDURE:
1. Create the Email Registration Form:
Below is the basic HTML and ASP.NET markup for an email registration form with various
validation controls.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="Email1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Name<br />
&nbsp;Enter Your Email
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email is required"
ForeColor="Red"
Display="Dynamic">
</asp:RequiredFieldValidator>
&nbsp;<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Invalid email format"
ForeColor="Red"
Display="Dynamic"
ValidationExpression="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$">
</asp:RegularExpressionValidator>
&nbsp;<asp:CustomValidator ID="cvEmailLength" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email length must be between 5 and 50 characters"
ForeColor="Red"
Display="Dynamic"

10
OnServerValidate="ValidateEmailLength">
</asp:CustomValidator>
&nbsp;<asp:CustomValidator ID="cvEmailExists" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email already exists"
ForeColor="Red"
Display="Dynamic"
OnServerValidate="CheckEmailExists">
</asp:CustomValidator>
<script>
function validateEmail() {
var email = document.getElementById('<%= txtEmail.ClientID %>').value;
var regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!regex.test(email)) {
alert("Invalid email format!");
return false;
}
return true;
}
</script>

<br />

</form>
</body>
</html>

2. Add Code Behind File Default.aspx.cs


using System;

11
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Email1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ValidateEmailLength(object source, ServerValidateEventArgs args)
{
int length = args.Value.Length;
args.IsValid = (length >= 5 && length <= 50);
}
protected void CheckEmailExists(object source, ServerValidateEventArgs args)
{
string email = args.Value;
bool emailExists = CheckIfEmailExists(email); // Function to check in DB
args.IsValid = !emailExists;
}
private bool CheckIfEmailExists(string email)
{
// Simulated database check (Replace with actual database query)
List<string> existingEmails = new List<string> { "[email protected]",
"[email protected]" };
return existingEmails.Contains(email);
}
}
}
3. Add Web.Config File
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />

12
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" warningLevel="4"
compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" warningLevel="4"
compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\
&quot; /optionInfer+" />
</compilers>
</system.codedom>
</configuration>

4. Run Your Project

13
Ex.4. Create an application using Data grid control to access information’s from table in
SQL server.

14
Aim:
Creating an application that uses a DataGrid control to display and access information from an
SQL Server table can be done in various frameworks and languages. Below is an example using
C# with Windows Forms (WinForms), one of the most common ways to achieve this in .NET.
This application will:
1. Connect to an SQL Server database.
2. Fetch data from a table.
3. Display the data in a DataGridView control.
4. Allow users to update, delete, or add records.
SQL Code:
CREATE DATABASE SampleDB;

USE SampleDB;

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY IDENTITY(1,1),
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Position NVARCHAR(50),
Salary DECIMAL(18,2)
);

INSERT INTO Employees (FirstName, LastName, Position, Salary)


VALUES ('John', 'Doe', 'Manager', 75000),
('Jane', 'Smith', 'Developer', 65000),
('Emily', 'Davis', 'Designer', 55000);

Implementation in C#
1. Create a Windows Forms Application:
 Open Visual Studio and create a new Windows Forms App (.NET Framework) project.
2. Design the Form:

15
 Add a DataGridView control from the toolbox to the form.
 Add buttons for operations like Refresh, Update, Add, and Delete.
3. Code the Application:
Below is the full implementation:
csharp
Copy code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DataGridExample
{
public partial class MainForm : Form
{
private string connectionString =
"Server=YOUR_SERVER_NAME;Database=SampleDB;Trusted_Connection=True;";
private SqlDataAdapter dataAdapter;
private DataTable dataTable;

public MainForm()
{
InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)


{
LoadData();
}

private void LoadData()

16
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Employees";
dataAdapter = new SqlDataAdapter(query, connection);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

dataTable = new DataTable();


dataAdapter.Fill(dataTable);

dataGridView1.DataSource = dataTable;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void btnRefresh_Click(object sender, EventArgs e)


{
LoadData();
}

private void btnUpdate_Click(object sender, EventArgs e)


{
try
{

17
dataAdapter.Update(dataTable);
MessageBox.Show("Changes saved to the database.");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void btnAdd_Click(object sender, EventArgs e)


{
try
{
DataRow newRow = dataTable.NewRow();
// Set default values for the new row (or let the user edit it in the grid)
newRow["FirstName"] = "New";
newRow["LastName"] = "Employee";
newRow["Position"] = "Unknown";
newRow["Salary"] = 0;
dataTable.Rows.Add(newRow);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void btnDelete_Click(object sender, EventArgs e)


{
try
{

18
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (!row.IsNewRow)
{
dataGridView1.Rows.RemoveAt(row.Index);
}
}
dataAdapter.Update(dataTable);
MessageBox.Show("Selected rows deleted.");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}

4. Steps to Wire Up the Form:


1. Drag a DataGridView onto the form (dataGridView1).
2. Add four buttons:
o Refresh (btnRefresh)
o Update (btnUpdate)
o Add (btnAdd)
o Delete (btnDelete)
3. Double-click each button to generate their click event handlers and paste the
corresponding code from above.

Features of the Application:


1. Display Data: Fetches all records from the Employees table and displays them in the
DataGridView.

19
2. Add Record: Adds a new row to the grid, which can then be saved to the database.
3. Update Record: Allows editing directly in the grid and saves changes to the database.
4. Delete Record: Deletes the selected rows and updates the database.

Sample Output:
When you run the application, you will see:
 A grid displaying the Employees table data.
 Buttons to refresh, add, update, and delete data.

Notes:
 Replace YOUR_SERVER_NAME in the connection string with your SQL Server name or
instance.
 Ensure the SQL Server database allows connections.
 Error handling is added for robustness, but it can be expanded further for better user
feedback.

Ex.05 Create an application using Data list control to access information’s from table in
SQL server and display the result in neat format
AIM
creating an application using Data List Control to fetch and display data from a SQL
Server database in a neat format. The example assumes you’re building this in a web application
using ASP.NET and C#.
Steps to Build the Application:
1. Set up your SQL Server Table
For this example, assume you have a table called Employees with the following structure:
sql
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Department NVARCHAR(50),
Email NVARCHAR(100)
);

20
2. Set up the ASP.NET Web Application
o Create a new ASP.NET Web Forms application.
3. Connect to SQL Server
Configure your connection string in the web.config file:
xml
<configuration>
<connectionStrings>
<add name="DBConnection"
connectionString="Server=YOUR_SERVER;Database=YOUR_DATABASE;Trusted_Connectio
n=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
4. Create the ASPX Page
The DataList control is used to display data in a formatted way.
Default.aspx:
html
Copy code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>

<!DOCTYPE html>
<html>
<head>
<title>Employee List</title>
<style>
.employee-card {
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
margin: 10px;
width: 300px;
display: inline-block;

21
box-shadow: 2px 2px 10px #ccc;
}
.employee-card h3 {
margin: 0;
color: #333;
}
.employee-card p {
margin: 5px 0;
color: #666;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h1>Employee List</h1>
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal"
RepeatColumns="2">
<ItemTemplate>
<div class="employee-card">
<h3><%# Eval("FirstName") %> <%# Eval("LastName") %></h3>
<p><strong>Department:</strong> <%# Eval("Department") %></p>
<p><strong>Email:</strong> <%# Eval("Email") %></p>
</div>
</ItemTemplate>
</asp:DataList>
</form>
</body>
</html>
5. Code-behind to Fetch Data
Write the logic to fetch data from SQL Server and bind it to the DataList control.
Default.aspx.cs:

22
csharp
Copy code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}

private void BindDataList()


{
// Get connection string from web.config
string connectionString =
ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connectionString))


{
string query = "SELECT EmployeeID, FirstName, LastName, Department, Email FROM
Employees";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
da.Fill(dt);

23
// Bind the DataList to the DataTable
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
}
Features:
1. Data Display: The DataList control displays employee data in a styled card format.
2. Custom Styling: The employee information is presented in a visually appealing format
using CSS.
3. Scalability: The DataList supports multiple columns for efficient layout.
Final Output:
When the page is loaded, the application will display employee information like this:
markdown
Copy code
------------------------------------
| John Doe |
| Department: HR |
| Email: [email protected] |
------------------------------------
| Jane Smith |
| Department: IT |
| Email: [email protected] |
------------------------------------

Ex. 6 Prepare employee pay slip using SQL connection.

AIM
To create an employee pay slip using SQL connection in ASP.NET,
Procedure:
1. Database Design

24
Ensure you have a database with the necessary tables to store employee and payroll information.
For example:
Employee Table
Column Name Data Type Description
EmployeeID INT (PK) Unique ID for the employee
Name VARCHAR(100) Employee's name
Department VARCHAR(50) Department name
Designation VARCHAR(50) Job title
Payroll Table
Column Name Data Type Description
PayrollID INT (PK) Unique ID for payroll
EmployeeID INT (FK) Foreign key from Employee table
BasicSalary DECIMAL(10,2) Basic salary
Allowances DECIMAL(10,2) Allowances amount
Deductions DECIMAL(10,2) Deductions amount
NetSalary DECIMAL(10,2) Computed as Basic + Allowances - Deductions
PayDate DATE Payment date

2. ASP.NET Code
A. SQL Connection Setup
Use the SqlConnection class to connect to your database.
Connection String
xml
Copy code
<configuration>
<connectionStrings>
<add name="PayrollDB" connectionString="Data Source=YourServerName;Initial
Catalog=YourDatabaseName;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

25
B. Backend Code to Fetch Pay Slip Data
Create a function to retrieve the required payroll data for an employee.
Code-Behind (C#)
csharp
Copy code
using System;
using System.Data;
using System.Data.SqlClient;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int employeeId = 1; // Replace with dynamic employee ID
GetPaySlip(employeeId);
}
}

private void GetPaySlip(int employeeId)


{
string connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["PayrollDB"].ConnectionString
;

using (SqlConnection con = new SqlConnection(connectionString))


{
string query = @"
SELECT
E.EmployeeID,

26
E.Name,
E.Department,
E.Designation,
P.BasicSalary,
P.Allowances,
P.Deductions,
P.NetSalary,
P.PayDate
FROM
Employee E
INNER JOIN
Payroll P ON E.EmployeeID = P.EmployeeID
WHERE
E.EmployeeID = @EmployeeID";

using (SqlCommand cmd = new SqlCommand(query, con))


{
cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
con.Open();

SqlDataReader reader = cmd.ExecuteReader();


if (reader.HasRows)
{
while (reader.Read())
{
lblEmployeeName.Text = reader["Name"].ToString();
lblDepartment.Text = reader["Department"].ToString();
lblDesignation.Text = reader["Designation"].ToString();
lblBasicSalary.Text = reader["BasicSalary"].ToString();
lblAllowances.Text = reader["Allowances"].ToString();
lblDeductions.Text = reader["Deductions"].ToString();

27
lblNetSalary.Text = reader["NetSalary"].ToString();
lblPayDate.Text =
Convert.ToDateTime(reader["PayDate"]).ToString("dd/MM/yyyy");
}
}
else
{
lblMessage.Text = "No data found for the given employee ID.";
}
}
}
}
}

C. ASP.NET Frontend Design


HTML/ASP.NET
html
Copy code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PaySlip.aspx.cs"
Inherits="YourNamespace.PaySlip" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employee Pay Slip</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 50%; margin: auto; border: 1px solid #ccc; padding: 20px; text-align:
center;">
<h2>Employee Pay Slip</h2>
<table style="width: 100%; text-align: left;">

28
<tr>
<td><strong>Name:</strong></td>
<td><asp:Label ID="lblEmployeeName" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Department:</strong></td>
<td><asp:Label ID="lblDepartment" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Designation:</strong></td>
<td><asp:Label ID="lblDesignation" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Basic Salary:</strong></td>
<td><asp:Label ID="lblBasicSalary" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Allowances:</strong></td>
<td><asp:Label ID="lblAllowances" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Deductions:</strong></td>
<td><asp:Label ID="lblDeductions" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Net Salary:</strong></td>
<td><asp:Label ID="lblNetSalary" runat="server"></asp:Label></td>
</tr>
<tr>
<td><strong>Pay Date:</strong></td>
<td><asp:Label ID="lblPayDate" runat="server"></asp:Label></td>

29
</tr>
</table>
</div>
</form>
</body>
</html>

3. Output
When you access the page, it will fetch the employee details and payroll data from the database
and display it in the formatted pay slip.

4. Tips
 Make sure you handle SQL exceptions properly.
 For real-world applications, sanitize the input to prevent SQL injection attacks.
 Consider using stored procedures for better performance and maintainability.
 Implement proper authentication to restrict access to the pay slip data.

Ex.07 Design a banking application for doing deposit, withdrawal and balance enquiry in
aps.net
AIM
Create a simple design for a banking application in ASP.NET using the Model-View-
Controller (MVC) architecture. The application supports deposit, withdrawal, and balance
inquiry functionalities.
Application Overview:
1. Technology Stack:
o Frontend: Razor Views (HTML + C#)
o Backend: ASP.NET MVC Framework
o Database: SQL Server or in-memory storage for simplicity
2. Functionalities:

30
o Deposit money into an account
o Withdraw money from an account
o View account balance

1. Create the Project


 Create a new ASP.NET MVC Application in Visual Studio.
 Select "MVC" as the project template.

2. Database Design
Use an Account table to store user account details.
Table: Accounts
Column Name Data Type Description
AccountId int (Primary Key) Unique account identifier
AccountHolder nvarchar(100) Name of the account holder
Balance decimal(18,2) Current balance

3. Model
Create a model class for the Account.
Account.cs
namespace BankingApp.Models
{
public class Account
{
public int AccountId { get; set; }
public string AccountHolder { get; set; }
public decimal Balance { get; set; }
}
}

4. Controller
Create a controller named AccountController.

31
AccountController.cs
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BankingApp.Models;

namespace BankingApp.Controllers
{
public class AccountController : Controller
{
// In-memory data storage for simplicity
private static List<Account> accounts = new List<Account>
{
new Account { AccountId = 1, AccountHolder = "John Doe", Balance = 1000 },
new Account { AccountId = 2, AccountHolder = "Jane Smith", Balance = 2000 }
};

// GET: Account/Index
public ActionResult Index()
{
return View(accounts);
}

// GET: Account/Details/1
public ActionResult Details(int id)
{
var account = accounts.FirstOrDefault(a => a.AccountId == id);
if (account == null)
{
return HttpNotFound();
}

32
return View(account);
}

// GET: Account/Deposit/1
public ActionResult Deposit(int id)
{
var account = accounts.FirstOrDefault(a => a.AccountId == id);
if (account == null)
{
return HttpNotFound();
}
return View(account);
}

// POST: Account/Deposit/1
[HttpPost]
public ActionResult Deposit(int id, decimal amount)
{
var account = accounts.FirstOrDefault(a => a.AccountId == id);
if (account != null && amount > 0)
{
account.Balance += amount;
return RedirectToAction("Details", new { id });
}
ModelState.AddModelError("", "Invalid deposit amount.");
return View(account);
}

// GET: Account/Withdraw/1
public ActionResult Withdraw(int id)
{

33
var account = accounts.FirstOrDefault(a => a.AccountId == id);
if (account == null)
{
return HttpNotFound();
}
return View(account);
}

// POST: Account/Withdraw/1
[HttpPost]
public ActionResult Withdraw(int id, decimal amount)
{
var account = accounts.FirstOrDefault(a => a.AccountId == id);
if (account != null && amount > 0 && account.Balance >= amount)
{
account.Balance -= amount;
return RedirectToAction("Details", new { id });
}
ModelState.AddModelError("", "Invalid withdrawal amount or insufficient balance.");
return View(account);
}
}
}

5. Views
Create views for the Index, Details, Deposit, and Withdraw actions.
Index.cshtml
@model List<BankingApp.Models.Account>

<h2>Accounts</h2>
<table class="table">

34
<thead>
<tr>
<th>Account ID</th>
<th>Account Holder</th>
<th>Balance</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var account in Model)
{
<tr>
<td>@account.AccountId</td>
<td>@account.AccountHolder</td>
<td>@account.Balance</td>
<td>
@Html.ActionLink("View Details", "Details", new { id = account.AccountId })
</td>
</tr>
}
</tbody>
</table>

Details.cshtml
@model BankingApp.Models.Account

<h2>Account Details</h2>
<p>Account ID: @Model.AccountId</p>
<p>Account Holder: @Model.AccountHolder</p>
<p>Balance: @Model.Balance</p>

35
<p>
@Html.ActionLink("Deposit", "Deposit", new { id = Model.AccountId }) |
@Html.ActionLink("Withdraw", "Withdraw", new { id = Model.AccountId }) |
@Html.ActionLink("Back to List", "Index")
</p>

Deposit.cshtml
html
Copy code
@model BankingApp.Models.Account

<h2>Deposit Money</h2>
@using (Html.BeginForm())
{
<p>Account Holder: @Model.AccountHolder</p>
<p>Current Balance: @Model.Balance</p>

<div class="form-group">
<label>Amount to Deposit</label>
<input type="number" name="amount" class="form-control" step="0.01" />
</div>

<button type="submit" class="btn btn-primary">Deposit</button>


}
<p>@Html.ActionLink("Back to Details", "Details", new { id = Model.AccountId })</p>

Withdraw.cshtml
html
Copy code
@model BankingApp.Models.Account

36
<h2>Withdraw Money</h2>
@using (Html.BeginForm())
{
<p>Account Holder: @Model.AccountHolder</p>
<p>Current Balance: @Model.Balance</p>

<div class="form-group">
<label>Amount to Withdraw</label>
<input type="number" name="amount" class="form-control" step="0.01" />
</div>

<button type="submit" class="btn btn-primary">Withdraw</button>


}
<p>@Html.ActionLink("Back to Details", "Details", new { id = Model.AccountId })</p>

6. Run the Application


1. Start the application.
2. Navigate to /Account/Index to see the list of accounts.
3. Perform deposit, withdrawal, and balance inquiries via the provided actions.
This design uses in-memory storage for simplicity. For a production-ready application, connect
to a database using Entity Framework.

Ex. 07 Demonstrate the file upload control usage in asp.net


AIM
To demonstrate the usage of a file upload control in ASP.NET, we can use the FileUpload server
control along with a Button and a Label to display the uploaded file information. Below is a
simple example:

Steps:
1. Add the FileUpload control to your page to allow file selection.
2. Add a Button to trigger the upload process.
3. Use a Label to display messages (success/failure or file information).

37
4. Handle the file upload logic in the server-side code.

Code Example:
ASP.NET Markup (Default.aspx)
asp.net
Copy code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="FileUploadDemo.Default" %>

<!DOCTYPE html>
<html>
<head>
<title>ASP.NET File Upload Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>File Upload Example in ASP.NET</h2>
<!-- FileUpload control -->
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />

<!-- Upload button -->


<asp:Button ID="btnUpload" runat="server" Text="Upload File"
OnClick="btnUpload_Click" />
<br /><br />

<!-- Label to display status -->


<asp:Label ID="lblMessage" runat="server" ForeColor="Green"></asp:Label>
</div>
</form>

38
</body>
</html>

Code-behind (Default.aspx.cs)
csharp
Copy code
using System;
using System.IO;

namespace FileUploadDemo
{
public partial class Default : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
// Check if a file has been selected
if (FileUpload1.HasFile)
{
try
{
// Define the file path to save the uploaded file
string folderPath = Server.MapPath("~/Uploads/");

// Ensure the directory exists


if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}

// Save the file


string filePath = folderPath + Path.GetFileName(FileUpload1.FileName);

39
FileUpload1.SaveAs(filePath);

// Display success message


lblMessage.Text = "File uploaded successfully! File path: " + filePath;
}
catch (Exception ex)
{
// Display error message
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Error: " + ex.Message;
}
}
else
{
// No file selected
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file to upload.";
}
}
}
}

Explanation:
1. FileUpload Control:
o The FileUpload control provides an interface for selecting a file.
o The HasFile property checks if a file has been selected.
2. Button:
o When the Button is clicked, the btnUpload_Click event handler processes the
uploaded file.
3. Saving the File:

40
o The file is saved using the SaveAs method, and the path is specified using
Server.MapPath.
4. Message Display:
o The Label control shows messages, such as upload success or failure, to the user.

Folder Setup:
 Create a folder named Uploads in the root directory of your project (or let the code create
it dynamically).

Output:
1. When a file is selected and uploaded:
o A success message is displayed, showing the file path.
2. If no file is selected:
o An error message prompts the user to select a file.
3. If an error occurs during upload:
o An error message is displayed with the exception details.

Enhancements:
 File Type Validation: Add checks for specific file types using Path.GetExtension().
 File Size Validation: Use FileUpload1.PostedFile.ContentLength to validate file size.
 Security: Sanitize file names to avoid overwriting and prevent malicious file uploads.

Ex.No.08 Design a web page to display the advertisements using Ad Rotator Control in
asp.net
To design a web page that displays advertisements using the Ad Rotator Control in
ASP.NET, follow these steps:

Step 1: Create an XML File for Advertisements


The Ad Rotator Control fetches ad data from an XML file that contains information about the
ads, such as the image URL, navigation URL, and impressions.
Example: Ads.xml
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>

41
<ImageUrl>1.jpg</ImageUrl>
<NavigateUrl>https://www.example1.com</NavigateUrl>
<AlternateText>Ad 1</AlternateText>
<Impressions>50</Impressions>
</Ad>
<Ad>
<ImageUrl>3.jpg</ImageUrl>
<NavigateUrl>https://www.example2.com</NavigateUrl>
<AlternateText>Ad 2</AlternateText>
<Impressions>30</Impressions>
</Ad>
<Ad>
<ImageUrl>4.jpg</ImageUrl>
<NavigateUrl>https://www.example3.com</NavigateUrl>
<AlternateText>Ad 3</AlternateText>
<Impressions>20</Impressions>
</Ad>
</Advertisements>

Step 2: Create the ASP.NET Web Page


Create an ASP.NET Web Form (e.g., Default.aspx) and add the AdRotator Control.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Ex9_AD.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Ad Rotator Example</h2>
<br />
<asp:AdRotator ID="AdRotator2" runat="server" AdvertisementFile="~/XMLFile1.xml" target="_blank" />

</div>
</form>
</body>
</html>

Step 3: Add Images to the Project


Place your advertisement images (e.g., ad1.jpg, ad2.jpg, ad3.jpg) in a folder called Images
within the project directory.

Step 4: Run the Application


1. Add the Ads.xml file to a folder (e.g., Ads) in your project.
2. Add the advertisement images to the Images folder.
3. Build and run the project to see the advertisements rotating on the web page.

42
1.

FileUpload Control Example in ASP.Net


Step 1 – Open the Visual Studio –> Create a new empty Web application.
Step 2 – Create a New web page for display FileUpload control.
Step 3 – Drag and drop FileUpload control on web page along with one Button
control from Toolbox.

WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="FileUpload1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
else
{
Label1.Text = "Select image first !!";
}<body>
<form id="form1" runat="server">
<div>

<table align="center" class="style1" style="border: thin solid #008080">


<tr>
<td class="style2"
style="text-align: center; border-bottom-style: solid; border-bottom-width: thin;
border-bottom-color: #008080;">
FileUpload Control in ASP.Net</td>
</tr>
<tr>
<td style="text-align: center">&nbsp;
&nbsp;
</td>
</tr>
<tr>

43
<td style="text-align: center">
Select File :
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="btnupload" runat="server" onclick="btnupload_Click"
style="font-weight: 700" Text="Upload" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:Image ID="Image1" runat="server" Height="136px" Width="123px" />
</td>
</tr>
</table>

</div>
</form></body>
</html>

Step 4 – Write server side code in button click event for upload image using
FileUpload control.
Step 5 – Create new folder “img” in solution explorer to store images.

44
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace file
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnupload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/img/") + FileUpload1.FileName);
Image1.ImageUrl = "~/img/" + FileUpload1.FileName;
Label1.Text = "Image Uploaded Successfully !!";
}

}
}
}

45
46

You might also like