0% found this document useful (0 votes)
16 views28 pages

Unit - 3 Rich & Validation Controls

The document discusses Rich Controls in ASP.NET, which enhance user interface and functionality, including examples like Calendar, AdRotator, and FileUpload controls. It also covers Validation Controls, explaining their importance in ensuring valid user input, with types such as RequiredFieldValidator, CompareValidator, and RangeValidator. Additionally, it introduces the FileStream class for file operations in C#, detailing its constructors, modes, access, and sharing options.

Uploaded by

Sneha Sb
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)
16 views28 pages

Unit - 3 Rich & Validation Controls

The document discusses Rich Controls in ASP.NET, which enhance user interface and functionality, including examples like Calendar, AdRotator, and FileUpload controls. It also covers Validation Controls, explaining their importance in ensuring valid user input, with types such as RequiredFieldValidator, CompareValidator, and RangeValidator. Additionally, it introduces the FileStream class for file operations in C#, detailing its constructors, modes, access, and sharing options.

Uploaded by

Sneha Sb
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

UNIT-3

3.1 Rich Controls in [Link]


Rich Controls are advanced, high-level web controls in [Link] that provide enhanced
functionality and a better user interface compared to standard controls.

Definition

 Rich Controls are web controls that support complex user interactions.
 They go beyond basic input controls like TextBox and Button.
 There is no strict definition, but any control offering extended features is considered a
Rich Control.

Features

 Improve user experience with dynamic behavior


 Handle complex input and display
 Provide additional built-in functionality
 Make web applications more interactive

Examples of Rich Controls

 Calendar Control
 AdRotator Control
 FileUpload Control
 MultiView and View Controls
 Wizard Control

3.1.1 Calendar Control


Definition

The Calendar Control is used to display a graphical calendar on a web page.


It allows users to select one or more dates and is commonly used as a Date Picker.

Uses

 Displays one month at a time


 Allows navigation between months
 Enables selection of dates
Properties of Calendar Control

1. SelectionMode
o Specifies how dates are selected
o Values: Day, DayWeek, DayWeekMonth, None
2. SelectedDate
o Used to get or set the selected date(s)
3. ShowTitle
o Shows or hides the calendar title
4. NextMonthText
o Sets the text for the next month navigation link

Events of Calendar Control

1. SelectionChanged
o Occurs when a new date is selected
2. VisibleMonthChanged
o Occurs when the user changes the month

Example Code (Calendar Control)

ASPX
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged" />
<asp:Label ID="Label1" runat="server"></asp:Label>

C# (Code-behind)
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
[Link] = "Selected Date: " + [Link];
}

Explanation

 Calendar allows the user to select a date


 SelectedDate gets the chosen date
 The selected date is displayed in the Label
3.1.2 AdRotator Control
Definition

The AdRotator Control is used to display a sequence of advertisement images on a web page.
Each time the page is loaded, an image is selected randomly from a list.

Uses

 Display banner advertisements


 Rotate images dynamically
 Show random images on page refresh

Properties of AdRotator Control

1. ImageUrlField
o Specifies the image URL
o Default value: ImageUrl
2. AlternateText
o Displays alternate text for the image
3. Impression
o Controls how often an ad appears
4. NavigateUrl
o Specifies the link for the advertisement
5. DataSource
o Specifies the data source (usually XML)
6. Height
o Sets the height of the banner
7. Width
o Sets the width of the banner

Example for AdRotator

ASPX
<asp:AdRotator ID="AdRotator1" runat="server"
DataSourceID="XmlDataSource1" />

<asp:XmlDataSource ID="XmlDataSource1" runat="server"


DataFile="~/[Link]" />
XML ([Link])
<Advertisements>
<Ad>
<ImageUrl>image/[Link]</ImageUrl>
<NavigateUrl>[Link]</NavigateUrl>
<AlternateText>Ad Image</AlternateText>
</Ad>
</Advertisements>

Explanation

 AdRotator displays advertisement images


 Ads are stored in an XML file
 Image changes randomly on page refresh

3.1.3 FileUpload Control


Definition

The FileUpload Control allows users to browse and upload files to the server.

Uses

 Upload files from client to server


 Used with a Button control
 Files are saved using SaveAs() method

Properties of FileUpload Control

Property Description
FileBytes Returns file as byte array
FileContent Returns file stream
FileName Returns uploaded file name
HasFile Checks if file is selected
PostedFile Returns uploaded file reference

Events of FileUpload Control

1. Init – When control is initialized


2. Load – When control loads
3. PreRender – Before rendering
4. Unload – When control is unloaded
5. Disposed – When released from memory
6. DataBinding – When data is bound

FileUpload Example Code

ASPX
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server"
Text="Upload" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>

C# (Code-behind)
protected void Button1_Click(object sender, EventArgs e)
{
[Link]("C:/" + [Link]);
[Link] = "File uploaded successfully";
}

Explanation

 FileUpload allows users to upload files


 SaveAs() saves the file to the server
 Label shows upload confirmation

Summary
 Rich Controls enhance UI and functionality
 Calendar Control is used for date selection
 AdRotator Control displays rotating advertisements
 FileUpload Control uploads files to the server

What is XML?

XML (eXtensible Markup Language) is used to store and transport data in a structured and
readable format.
3.2 Validation Controls in [Link]
Validation controls in [Link] are used to check the correctness of user input before the data
is processed or stored.
They help ensure that the data entered by the user is valid, complete, and in the correct format.

Why Validation Controls are needed

 User input cannot always be trusted


 Invalid data may cause errors or incorrect results
 [Link] provides built-in validation controls to avoid writing complex scripts

Validation can be done:

 On client side (browser)


 On server side

Types of Validation Controls in [Link]


1. RequiredFieldValidator
2. CompareValidator
3. RangeValidator

3.2.1 Required Field Validator


Definition

The RequiredFieldValidator control ensures that the user must enter a value in the input field
before submitting the form.

If the field is left empty, an error message is displayed.

Use

 To prevent blank input


 Commonly used for Name, Email, Password fields

Important Properties of RequiredFieldValidator

Property Description
ID Unique identifier for the validator
runat Specifies that the control runs on the server
Property Description
ControlToValidate ID of the input control to be validated
Text Error message displayed when validation fails
ErrorMessage Message shown when validation fails
IsValid Boolean value indicating whether input is valid
InitialValue Default value treated as empty
ForeColor Color of error message
Display Controls how the error message is shown
Enabled Enables or disables validation

Display Property Values

 None – Validator is not displayed


 Static – Error message space is reserved
 Dynamic – Error message appears only when validation fails

Syntax Example (RequiredFieldValidator)


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator
ID="Required"
runat="server"
ControlToValidate="TextBox1"
Text="FIELD CANNOT BE BLANK">
</asp:RequiredFieldValidator>

Output

If the user clicks submit without entering text, the message


“FIELD CANNOT BE BLANK” will be displayed.

3.2.2 Compare Validator


Definition

The CompareValidator is used to compare values between:

 Two input controls


OR
 One control and a fixed value

Uses

 Compare password & confirm password


 Compare two numbers
 Validate date or numeric format

Important Properties of CompareValidator

Property Description
ControlToValidate Input control to validate
ControlToCompare Input control to compare with
ValueToCompare Fixed value for comparison
Operator Type of comparison
Type Data type (String, Integer, Date, Double, Currency)
Text Error message

Operator Values

 Equal
 NotEqual
 GreaterThan
 GreaterThanEqual
 LessThan
 LessThanEqual
 DataTypeCheck

Compare Validator Example


<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>

<asp:CompareValidator
ID="compval"
runat="server"
ControlToValidate="txt1"
ControlToCompare="txt2"
Type="String"
Text="Validation Failed!">
</asp:CompareValidator>

Output
If both values are not equal, the message
“Validation Failed!” is displayed.

3.2.3 Range Validator


Definition

The RangeValidator checks whether the input value falls between a minimum and maximum
value.

Uses

 Validate Age
 Validate Marks
 Validate Date range

Important Properties of RangeValidator

Property Description
ControlToValidate Input control to validate
MinimumValue Minimum allowed value
MaximumValue Maximum allowed value
Type Data type (Integer, Date, String, etc.)
Text Error message

Example 1: Age Validation


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RangeValidator
ID="range"
runat="server"
ControlToValidate="TextBox1"
MinimumValue="18"
MaximumValue="35"
Text="Invalid Age">
</asp:RangeValidator>

Output
If the age entered is less than 18 or greater than 35,
“Invalid Age” will be displayed.

Example 2: Date Validation


<asp:TextBox ID="tbox1" runat="server"></asp:TextBox>

<asp:RangeValidator
ID="RangeValidator1"
runat="server"
ControlToValidate="tbox1"
MinimumValue="2005-01-01"
MaximumValue="2005-12-31"
Type="Date"
Text="The date must be between 2005-01-01 and 2005-12-31">
</asp:RangeValidator>

Summary
 RequiredFieldValidator → Checks empty input
 CompareValidator → Compares two values
 RangeValidator → Checks value within range
 Validation controls reduce manual coding
 Improves data accuracy and reliability
FileStream Class
What is FileStream?

FileStream is a class in C# that is used to read from and write to files.

 It supports reading, writing, and both


 It works with files stored on disk
 It supports synchronous and asynchronous operations

👉 It belongs to the [Link] namespace.

using [Link];

Why FileStream is used

 To create a file
 To open an existing file
 To read data from a file
 To write data into a file
 To append data at the end of a file

FileStream Constructors
1. FileStream(string path, FileMode mode)
FileStream fs = new FileStream("[Link]", [Link]);

Explanation

This constructor creates a FileStream object using:

 path → location of the file


 mode → how the file should be opened or created

Parameters:

1. path
o Can be absolute or relative
o Example: "C:\\Files\\[Link]" or "[Link]"
2. mode
o Uses FileMode enum
o Decides whether to create, open, append, etc.

2. FileStream(string path, FileMode mode, FileAccess access)


FileStream fs = new FileStream("[Link]", [Link], [Link]);
Parameters:

1. path → file location


2. mode → file creation/opening rule
3. access → read / write / readwrite permission

👉 This constructor also controls:

 CanRead
 CanWrite
 CanSeek

3. FileStream(string path, FileMode mode, FileAccess access, FileShare share)


FileStream fs = new FileStream(
"[Link]",
[Link],
[Link],
[Link]
);
Parameters:

1. path → file path


2. mode → how file is opened
3. access → read/write permission
4. share → how other processes can access the file

FileMode
FileMode decides how the operating system opens or creates a file.

public enum FileMode


{
CreateNew = 1,
Create = 2,
Open = 3,
OpenOrCreate = 4,
Truncate = 5,
Append = 6
}
1. CreateNew

 Creates a new file


 ❌ If file already exists → IOException
 Requires write permission

[Link]

2. Create

 Creates a new file


 ✔ If file exists → overwrites it
 Requires write permission

[Link]

3. Open

 Opens an existing file


 ❌ If file does not exist → FileNotFoundException
 Access depends on FileAccess

[Link]

4. OpenOrCreate

 Opens file if it exists


 Otherwise creates a new file
 Permissions depend on FileAccess

[Link]

5. Truncate

 Opens an existing file


 Deletes all content (length = 0)
 ❌ File must already exist
 ❌ Reading is not allowed

[Link]
6. Append

 Opens file and adds data at the end


 Creates file if it doesn’t exist
 ✔ Only works with [Link]
 ❌ Seeking to other positions causes exception

[Link]

FileAccess
FileAccess decides what operations are allowed on a file.

public enum FileAccess


{
Read = 1,
Write = 2,
ReadWrite = 3
}

1. Read

 Allows only reading


 Data cannot be modified

[Link]

2. Write

 Allows only writing


 Data can be added or modified
 Reading not allowed

[Link]

3. ReadWrite

 Allows both reading and writing


 Full access to file

[Link]
FileShare
FileShare controls how a file can be shared with other processes while it is open.

public enum FileShare


{
None = 0,
Read = 1,
Write = 2,
ReadWrite = 3
}

Common FileShare values

1. None

 No other process can access the file

[Link]

2. Read

 Others can read the file


 Cannot write

[Link]

3. Write

 Others can write to the file


 Cannot read

[Link]

4. ReadWrite

 Others can read and write

[Link]
READING AND WRITING TO FILES

StreamWriter Class (Writing data to file)


What is StreamWriter?

 Used to write text data into a file


 If file does not exist → it will create
 If file exists → it will overwrite (default)

StreamWriter Class – Definition

The StreamWriter class in C# is used to write text data to a file in a sequential manner. It
belongs to the [Link] namespace and provides an efficient way to create, write, and store
text information into files. StreamWriter works with character data and supports different
encodings. If the specified file does not exist, the StreamWriter class automatically creates a new
file, and if the file already exists, it overwrites the existing content by default. It is commonly
used for saving user input, writing log files, and storing application data permanently.

Used mostly for:

 Saving user input


 Writing logs
 Storing text data

Constructor of StreamWriter

StreamWriter sw = new StreamWriter("D:\\[Link]");

Meaning:

 Creates a file named [Link]


 Location → D drive
 Opens the file for writing

Important Methods of StreamWriter

Method Meaning (Simple)


Write() Writes text (no new line)
WriteLine() Writes text + moves to next line
Flush() Sends buffered data to file
Close() Closes the file properly
Dispose() Frees resources
🔹 Simple Example: Writing to a File

using System;
using [Link];

class Program
{
static void Main()
{
StreamWriter sw = new StreamWriter("D:\\[Link]");

[Link]("Enter text:");
string data = [Link]();

[Link](data);
[Link]();

[Link]("Data written successfully");


[Link]();
}
}

Line-by-Line Explanation

StreamWriter sw = new StreamWriter("D:\\[Link]");

➡ Creates file and opens it for writing

string data = [Link]();

➡ Takes input from user

[Link](data);

➡ Writes data into file

[Link]();

➡ Saves and closes file (VERY IMPORTANT)

StreamReader Class (Reading data from file)


What is StreamReader?

 Used to read text from a file


 Reads data line by line

StreamReader Class – Definition

The StreamReader class in C# is used to read text data from a file efficiently. It is also part of
the [Link] namespace and reads characters from a byte stream using a specified or default
encoding (UTF-8). StreamReader reads data sequentially, usually line by line, until the end of
the file is reached. It is widely used for reading text files, configuration files, and stored data in
C# and [Link] applications.

🔹 Simple Example: Reading a File

using System;
using [Link];

class Program
{
static void Main()
{
StreamReader sr = new StreamReader("D:\\[Link]");

string line = [Link]();


while (line != null)
{
[Link](line);
line = [Link]();
}

[Link]();
[Link]();
}
}

Line-by-Line Explanation
StreamReader sr = new StreamReader("D:\\[Link]");
➡ Opens file for reading
string line = [Link]();
➡ Reads one line from file
while (line != null)
➡ Loop continues till end of file
[Link]();

➡ Closes file

File Operations
Introduction

In C#, file handling is used to store, retrieve, modify, and manage data permanently in a
computer system. The [Link] class provides static methods that allow programmers to
perform common file operations without creating objects. It helps in handling files easily such
as creating, copying, moving, renaming, and deleting files.

1️ Creating a File — [Link]()

Definition:

[Link]() is a method of the [Link] class used to create a new empty file at a
specified location.
If the file already exists, it overwrites the existing file.
This method returns a FileStream object, so the stream must be closed after creation to release
system resources.

Syntax:
FileStream fs = [Link]("path");

Example:
FileStream fs = [Link]("D:\\[Link]");
[Link]();

Explanation:

 A file named [Link] is created in the D drive


 The file will be empty
 Close() is mandatory to avoid file lock

Key Points:

✔ Creates a new file


✔ Overwrites existing file
✔ Returns FileStream
✔ Must close the stream

2️ Moving / Renaming a File — [Link]()

Definition:

[Link]() is used to move a file from one location to another.


If the source and destination paths have different file names, the method also performs
renaming.
This method is commonly used for organizing files.

Syntax:
[Link](sourcePath, destinationPath);

Example:
string source = "D:\\[Link]";
string destination = "E:\\[Link]";
[Link](source, destination);

Explanation:

 File is moved from D drive to E drive


 Original file is removed from source location
 If name is changed, it acts as rename

Key Points:

✔ Moves file location


✔ Can rename file
✔ Source file no longer exists

3️ Copying a File — [Link]()


Definition:

[Link]() is used to create a duplicate copy of a file at another location.


The original file remains unchanged.
An optional overwrite parameter decides whether an existing file should be replaced.

Syntax:
[Link](source, destination, overwrite);

Example:
string source = "D:\\[Link]";
string destination = "E:\\[Link]";
[Link](source, destination, true);

Explanation:

 A copy of [Link] is created as [Link]


 true allows overwriting if file already exists
 Original file stays safe

Key Points:

✔ Creates duplicate file


✔ Original file is preserved
✔ Supports overwrite option

4️ Deleting a File — [Link]()

Definition:

[Link]() is used to permanently remove a file from the system.


The deleted file cannot be recovered and does not go to the recycle bin.

Syntax:
[Link]("path");

Example:
string path = "E:\\[Link]";
[Link](path);

Explanation:
 File is removed permanently
 No confirmation or recycle bin

Key Points:

✔ Permanently deletes file


✔ No recycle bin
✔ File cannot be recovered

⭐ Important Exam Points

Method Purpose

StreamWriter Used for writing data into a file

StreamReader Used for reading data from a file

[Link]() Creates a new file

[Link]() Moves or renames a file

[Link]() Copies a file

[Link]() Deletes a file

Close() Releases file resources


File Uploading in [Link]
What is File Uploading?

File uploading is the process of sending a file from the client’s computer (user system) to the
web server.

In [Link], file uploading is done using the FileUpload server control, which allows the user
to:

 Select a file from their local system


 Upload it to the server
 Store it in a folder or process it programmatically

Why File Uploading is used

File uploading is commonly used for:

 Uploading profile photos


 Submitting assignments
 Uploading documents (PDF, Word, images)
 Storing files on the server
 Reading file content and saving it to a database

FileUpload Control

The FileUpload control is a server-side control in [Link] used to upload files from the client
to the server.

Syntax:
<asp:FileUpload ID="FileUpload1" runat="server" />

Working of File Uploading

1. User clicks the Browse button


2. Selects a file from the local computer
3. Clicks the Upload button
4. File is sent to the server
5. The file is saved using the SaveAs() method
SaveAs() Method
[Link](path);

Purpose:

 Saves the uploaded file to a specified folder on the server

📌 The path must be a server path, not a client path.

Properties of FileUpload Control

1. ID

 Gets or sets the unique identifier of the FileUpload control

2. HasFile

 Returns true if a file is selected


 Returns false if no file is selected

if ([Link])

3. PostedFile

 Returns the uploaded file as an HttpPostedFile object


 Contains:
o File name
o File size
o Content type
o Input stream

4. FileName

 Gets the name of the selected file from the client system

[Link]
5. Visible

 Decides whether the control is shown on the page

6. EnableViewState

 Maintains the state of the control during postback

Events of FileUpload Control


1. Init

 Occurs when the control is initialized

2. Load

 Occurs when the control is loaded into the page

3. PreRender

 Occurs just before the control is displayed on the page

4. Unload

 Occurs when the control is removed from memory

5. Disposed

 Occurs when the control is completely released


Steps to Implement FileUpload Control

Step 1: Create a Web Application

1. Open Visual Studio


2. Click File → New → Web Site
3. Select [Link] Empty Web Site
4. Click OK
5. Right-click on the website
6. Click Add New Item
7. Select Web Form
8. Click Add

Step 2: Design the Web Form

Drag and drop the following controls from the Toolbox:

 FileUpload
 Button
 Label

[Link] Code (Design Page)


<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Upload"
OnClick="Button1_Click" />
<br /><br />
<asp:Label ID="Label2" runat="server"></asp:Label>
Step 3: Code-Behind (C# Code)
using System;
using [Link];
using [Link];
using [Link];

public partial class Fileuploadcontrol : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)


{
if ([Link])
{
[Link]("I:/" + [Link]);

[Link] = "File " + [Link] +


" is uploaded successfully";
}
else
{
[Link] = "Please select a file to upload";
}
}
}

Explanation of Code
[Link]

 Checks whether the user selected a file

SaveAs()

 Saves the file to the I:\ drive on the server

[Link]

 Gets the name of the uploaded file


[Link]

 Displays success or error message

Step 4: Run the Program


1. Press F5
2. Click Browse
3. Select a file
4. Click Upload
5. File is saved on the server
6. Success message is displayed

Common questions

Powered by AI

Validation is critical in ASP.NET applications to ensure the correctness of user input before processing or storing the data. It prevents errors due to invalid data and enhances security by blocking malicious input. Validation controls in ASP.NET streamline this process by offering predefined checks such as RequiredFieldValidator and RangeValidator, which reduce the need for complex scripts and provide client-side and server-side validation .

FileMode controls how files are opened or created, offering options like Create, Open, and Append. FileAccess specifies permissions (Read, Write, ReadWrite) defining how the file can be accessed. FileShare determines how the file can be accessed by other processes, with options like Read and Write. These enums provide granular control over file operations, dictating file accessibility, safety, and concurrency .

The Calendar Control in ASP.NET enhances date selection by allowing users to pick single or multiple dates through a graphical interface. It supports navigation between months, can limit date selection modes (e.g., by day, week, or month), and triggers events such as SelectionChanged when a date is picked, thereby enabling seamless interaction and integration within web applications .

The Append FileMode is ideal when the task requires adding data to the end of an existing file without altering its original content, such as logging activities or accumulating user actions. Unlike Create, which overwrites existing data, Append maintains prior information while facilitating continuous data addition .

Rich Controls in ASP.NET offer enhanced functionality and a better user interface compared to standard controls. They improve user experience with dynamic behaviors, allow handling of complex input and display, and provide additional built-in functionalities that make web applications more interactive .

StreamReader is used for reading text data from files, operating line-by-line, while StreamWriter writes text data into files, often overwriting existing content. StreamReader focuses on input operations, while StreamWriter is optimized for output, supporting different text encodings. Both are part of System.IO but serve opposite roles in data handling .

Client-side validation occurs in the browser and provides immediate feedback to users, enhancing user experience by reducing server round-trips. Server-side validation, performed on the server, is essential for security and data integrity as client-side validation can be bypassed. The combination of both ensures robust validation without sacrificing performance .

In ASP.NET, XML serves as a structured and human-readable data source, which is particularly useful for controls like the AdRotator. XML files can store multiple advertisements with attributes for image URLs, navigation links, and alternate text, allowing easy updates and management without altering code, thus decoupling data management from application logic .

The SaveAs method in the FileUpload Control is crucial for saving uploaded files to a specified path on the server. It ensures that the file selected by the user is securely transferred and stored, enabling web applications to handle file submissions for purposes like document uploads and image storage efficiently .

The AdRotator Control facilitates dynamic advertisement display by randomly selecting and displaying advertisement images from an XML data source each time the page loads. It allows setting image URLs, links, and alternate text, and can manage ad appearance frequency through its properties, providing a flexible advertisement management system .

You might also like