C# Record
C# Record
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 />
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
}
}
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>();
7
// Hide the GridView initially until there is data to display
gridViewData.Visible = false;
}
}
8
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
}
}
4. Save and Run the Project
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 />
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>
<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>
<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>
<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>
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=\"Web\
" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
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;
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();
}
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);
dataGridView1.DataSource = dataTable;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
17
dataAdapter.Update(dataTable);
MessageBox.Show("Changes saved to the database.");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
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);
}
}
}
}
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;
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] |
------------------------------------
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;
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";
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.";
}
}
}
}
}
<!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
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>
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>
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 />
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/");
39
FileUpload1.SaveAs(filePath);
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:
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>
<!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>
42
1.
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>
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