ASP.NET — Study Notes

Unit 02

Server Controls — Master Pages, GridView, Validation Controls and the Login Control

13 Questions 2 & 5 Marks Server Controls
01
2 Marks Question

Differentiate between Master Page and Content Page

BasisMaster PageContent Page
DefinitionDefines the common layout and structure of multiple ASP.NET pages.A page that uses the Master Page and provides the actual page-specific content.
ExtensionUses .master extension.Usually uses .aspx extension.
ContentContains common elements such as header, menu, footer, etc.Contains controls and content specific to that particular page.
RelationshipActs as the template.Fills the defined ContentPlaceHolder areas of the Master Page.
PurposeMaintains a consistent design across the website.Displays individual page content while following the common layout.
In short The Master Page provides the common layout, while the Content Page provides the page-specific content within that layout.
02
2 Marks Question

Explain GridView and its Features

GridView is an ASP.NET server control used to display data from a data source in a tabular format. It is commonly used to display records retrieved from databases.

Features of GridView

Automatic Column Generation
Columns can be generated automatically using AutoGenerateColumns.
Sorting
Supports sorting of data.
Paging
Displays records across multiple pages.
Selection and Editing
Supports selection and editing of records.
Deleting Records
Deletes records when configured with appropriate data-source operations.
Field Types
Supports BoundField, TemplateField, ButtonField, etc.

Example

<asp:GridView ID="GridView1"
    runat="server"
    AutoGenerateColumns="true">
</asp:GridView>
Conclusion GridView provides a convenient way to display and manage tabular data in ASP.NET.
03
2 Marks Question

Explain RequiredFieldValidator and its Use

RequiredFieldValidator is an ASP.NET validation control used to ensure that a specified input field is not left empty. It checks whether the user has entered a value before the form is submitted.

Important Properties

ControlToValidate
Specifies the ID of the control to validate.
ErrorMessage
Specifies the message displayed when validation fails.
InitialValue
Specifies a value that is considered invalid, such as a default placeholder value.
Display
Controls how the error message is displayed.

Example

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

<asp:RequiredFieldValidator
    ID="rfvName"
    runat="server"
    ControlToValidate="txtName"
    ErrorMessage="Name is required." />
Use It is commonly used for mandatory fields such as Name, Username, Email, and Password.
04
2 Marks Question

Explain AutoPostBack with a Suitable Example

AutoPostBack is a property of ASP.NET server controls that determines whether a control should automatically submit the page back to the server when its value changes.

When AutoPostBack="true", the control immediately causes a postback when the relevant event occurs.

Example

<asp:DropDownList ID="ddlCity"
    runat="server"
    AutoPostBack="true"
    OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
    <asp:ListItem>Ahmedabad</asp:ListItem>
    <asp:ListItem>Surat</asp:ListItem>
</asp:DropDownList>

Code-behind:

protected void ddlCity_SelectedIndexChanged(
    object sender, EventArgs e)
{
    // Code executes automatically after selection changes
}

Here, when the user selects a different city, the page automatically posts back to the server and the SelectedIndexChanged event is executed.

In short AutoPostBack="true" allows a control to automatically send the page to the server when its value changes.
05
2 Marks Question

Explain Web.config and its Importance in ASP.NET

Web.config is an XML configuration file used in ASP.NET applications to store and manage application-level settings and configuration information.

Importance of Web.config

  • 01Stores database connection strings.
  • 02Configures authentication and authorization.
  • 03Controls session state and application settings.
  • 04Helps configure custom error handling.
  • 05Allows application settings to be changed without modifying the source code.

Example

<configuration>
    <appSettings>
        <add key="SiteName" value="My Website"/>
    </appSettings>
</configuration>
Conclusion Web.config provides a central place to configure and manage an ASP.NET application's settings.
06
2 Marks Question

Differentiate between Web Server Controls and HTML Server Controls

BasisWeb Server ControlsHTML Server Controls
DefinitionASP.NET controls that run on the server and generate HTML for the browser.Standard HTML elements that are made accessible to the server using runat="server".
SyntaxUses ASP.NET tags such as <asp:TextBox>, <asp:Button>.Uses normal HTML tags such as <input>, <button>, <select>.
FeaturesProvide rich properties, events, state management, and data binding.Provide more basic server-side control over standard HTML elements.
EventsSupport server-side events such as Click, TextChanged, etc.Can also be accessed and handled on the server when runat="server" is specified.
Example<asp:Button ID="btn1" runat="server" Text="Click" /><input id="btn1" type="button" runat="server" />
In short Web Server Controls are ASP.NET-specific controls with rich server-side functionality, while HTML Server Controls are standard HTML elements made available to server-side code.
07
2 Marks Question

Differentiate between Master Page and Content Page (Revisited)

BasisMaster PageContent Page
DefinitionProvides the common layout and structure for multiple pages.Provides the specific content for an individual page.
File ExtensionUses .master file.Usually uses .aspx file.
ContentContains common elements such as header, navigation and footer.Contains page-specific controls and information.
ContentPlaceHolderDefines ContentPlaceHolder controls where content can be inserted.Provides content for the Master Page's ContentPlaceHolder.
PurposeMaintains a consistent design throughout the website.Displays different content while using the common design.
In short The Master Page defines the common layout, while the Content Page supplies the individual page content.
08
5 Marks Question

Explain the Login Control with its Important Properties and a Suitable Example

The Login Control in ASP.NET is a ready-made server control used to provide a username and password login interface. It integrates with the ASP.NET Membership Provider, so developers do not need to create the complete login form manually.

Important Properties

  • 01UserName — Gets or sets the username entered by the user.
  • 02Password — Gets or sets the password entered by the user.
  • 03RememberMeSet — Determines whether the user's login should be remembered.
  • 04RememberMeText — Specifies the text displayed for the Remember Me option.
  • 05DestinationPageUrl — Specifies the page to which the user is redirected after successful login.
  • 06FailureText — Specifies the message displayed when login authentication fails.

Example

<asp:Login ID="loginCtrl" runat="server"
    DestinationPageUrl="~/Dashboard.aspx"
    FailureText="Invalid username or password. Try again." />

This creates a login form with username, password, and Remember Me functionality. If authentication is successful, the user is redirected to Dashboard.aspx; otherwise, the specified failure message is displayed.

Other ASP.NET Login Controls

LoginView
Displays different content for authenticated and anonymous users.
LoginStatus
Displays Login/Logout links.
LoginName
Displays the currently logged-in username.
PasswordRecovery
Helps users recover their password.
CreateUserWizard
Provides a step-by-step user registration form.
ChangePassword
Allows users to change their password.
Conclusion The Login Control simplifies user authentication by providing a ready-made login interface and authentication-related functionality.
09
5 Marks Question

Differentiate between Client-Side Validation and Server-Side Validation

Validation is the process of checking whether the data entered by the user is correct and follows the required rules. ASP.NET supports both client-side and server-side validation.

BasisClient-Side ValidationServer-Side Validation
ExecutionPerformed in the user's browser.Performed on the web server.
TechnologyGenerally uses JavaScript.Uses server-side code, such as C#.
SpeedFaster because no request is sent to the server.Slower because data must be sent to the server for validation.
Server LoadReduces server requests and load.Increases server processing and requests.
SecurityLess secure because client-side validation can be bypassed.More secure because validation is performed on the server.
UseUseful for immediate feedback to the user.Essential for validating data before processing or storing it.
ExampleChecking whether an email has the correct format in the browser.Checking submitted data against database/business rules on the server.

Example

ASP.NET validation controls can perform client-side validation using JavaScript and also perform server-side validation. Server-side validation should always be used for security because client-side validation can be bypassed.

<asp:RequiredFieldValidator
    ID="rfvName"
    runat="server"
    ControlToValidate="txtName"
    ErrorMessage="Name is required." />
In short Client-side validation is faster and provides immediate feedback, while server-side validation is more secure and reliable because the data is checked on the server.
10
5 Marks Question

Explain Validation Controls in ASP.NET with Suitable Examples

Validation Controls are ASP.NET server controls used to validate user input before the form is submitted or processed. They help ensure that the data entered by the user is correct and meets the required conditions.

Types of Validation Controls

01
RequiredFieldValidator

Checks whether a required field has been left empty.

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

<asp:RequiredFieldValidator
    ID="rfvName"
    runat="server"
    ControlToValidate="txtName"
    ErrorMessage="Name is required." />
02
CompareValidator

Compares the value of one control with another control or a specified value.

<asp:CompareValidator
    ID="cvPassword"
    runat="server"
    ControlToValidate="txtConfirm"
    ControlToCompare="txtPassword"
    ErrorMessage="Passwords do not match." />
03
RangeValidator

Checks whether the entered value falls within a specified range.

<asp:RangeValidator
    ID="rvAge"
    runat="server"
    ControlToValidate="txtAge"
    MinimumValue="18"
    MaximumValue="60"
    Type="Integer"
    ErrorMessage="Age must be between 18 and 60." />
04
RegularExpressionValidator

Validates input according to a specified regular expression pattern, such as an email or phone number format.

<asp:RegularExpressionValidator
    ID="revEmail"
    runat="server"
    ControlToValidate="txtEmail"
    ValidationExpression="^[^@\s]+@[^@\s]+\.[^@\s]+$"
    ErrorMessage="Enter a valid email." />
05
CustomValidator

Allows the developer to define custom validation logic when the built-in validators are not sufficient.

<asp:CustomValidator
    ID="cvCustom"
    runat="server"
    ControlToValidate="txtCode"
    ErrorMessage="Invalid code."
    OnServerValidate="ValidateCode" />
06
ValidationSummary

Displays the validation error messages together in one place.

<asp:ValidationSummary
    ID="ValidationSummary1"
    runat="server" />

Common Properties

ControlToValidate
Specifies which control should be validated.
ErrorMessage
Specifies the error message.
Display
Controls how the error message is displayed.
ValidationGroup
Groups related validation controls.
Conclusion ASP.NET Validation Controls help prevent invalid or incomplete data from being submitted and provide users with appropriate error messages.
11
5 Marks Question

Explain Theme in ASP.NET

An ASP.NET Theme is a mechanism used to provide a consistent appearance and styling to an ASP.NET web application. A Theme can define properties of server controls, such as colors, fonts, backgrounds and other control properties. It uses .skin files along with CSS files and is stored inside the App_Themes folder.

1. Theme Folder

Themes are stored in the special App_Themes folder. For example:

App_Themes/
    BlueTheme/
        BlueTheme.skin
        Site.css

The .skin file defines default properties for ASP.NET server controls, while CSS files can define the styling of the rendered HTML.

2. Creating a Theme

In Visual Studio: Right-click Project → Add → Add ASP.NET Folder → Theme. A theme folder is created inside App_Themes. It can then be renamed, for example, to BlueTheme.

3. Applying a Theme

A Theme can be applied in three ways.

A
Using Web.config

To apply the Theme to the entire website:

<system.web>
    <pages theme="BlueTheme" />
</system.web>
B
Using Page Directive

To apply it to a particular page:

<%@ Page Theme="BlueTheme" %>
C
Using Code-Behind

A Theme can also be assigned in the Page_PreInit event:

protected void Page_PreInit(object sender, EventArgs e)
{
    Page.Theme = "BlueTheme";
}
Note: When setting the Theme programmatically, it should be done in Page_PreInit, not Page_Load, because by Page_Load it is too late to apply the Theme to the controls.

4. .skin File

A .skin file defines the default appearance and properties of ASP.NET server controls. For example:

<asp:Button runat="server"
    BackColor="Blue"
    ForeColor="White"
    Font-Bold="true" />

This can automatically apply the specified properties to Button controls using the Theme. A SkinID can also be used when different styles are required for the same type of control:

<asp:Button
    runat="server"
    SkinID="DangerButton"
    Text="Delete" />

Thus, multiple skins can be created for the same control type within one Theme.

5. Theme vs StylesheetTheme

ThemeStylesheetTheme
Has higher priority.Has lower priority.
Overrides a control's own property settings.Can be overridden by the control's own properties.
Used when a consistent appearance must be enforced.Used when default styles should be provided but controls may customize them.

For example, if a Button has its own BackColor and the Theme also specifies BackColor, the Theme overrides the control's setting, whereas with StylesheetTheme, the control's explicit setting can override the theme.

Advantages of ASP.NET Themes

  • 01Provides a consistent look and feel throughout the application.
  • 02Allows styles for server controls to be defined centrally.
  • 03Reduces repeated styling code.
  • 04Makes it easier to change the appearance of an entire website.
  • 05Supports multiple skins for the same type of server control using SkinID.
Conclusion ASP.NET Themes provide a centralized way to manage the appearance of an application. They use App_Themes, .skin files, CSS and SkinID to apply consistent styles to server controls. A Theme can be applied at the application, page or code-behind level.
12
5 Marks Question

What is Master-Detail Relationship in Terms of Data Binding Controls? Demonstrate with an Example

A Master-Detail relationship in ASP.NET data binding is a relationship where one data-bound control displays a list of records (Master) and another data-bound control displays the details of the record selected in the Master control.

For example, in a college application:

  • 01Master: List of students displayed in a GridView.
  • 02Detail: Details of the selected student displayed in a DetailsView or another data-bound control.

ASP.NET provides data-binding controls such as GridView, FormView and Repeater for displaying data.

Example: Student Master-Detail

Suppose we have a Students table:

StudentIDNameCourse
1RahulBCA
2PriyaBCA
3AmitBBA

The GridView can act as the Master control and display all students. When the user selects Rahul, the Detail control can display Rahul's complete information.

Master Control — GridView

<asp:GridView ID="gvStudents"
    runat="server"
    AutoGenerateColumns="False"
    AutoGenerateSelectButton="True"
    DataKeyNames="StudentID"
    OnSelectedIndexChanged="gvStudents_SelectedIndexChanged">

    <Columns>
        <asp:BoundField DataField="StudentID"
            HeaderText="ID" />

        <asp:BoundField DataField="Name"
            HeaderText="Name" />

        <asp:BoundField DataField="Course"
            HeaderText="Course" />
    </Columns>

</asp:GridView>

The GridView displays the master list and provides a Select option for choosing a record.

Detail Control

A DetailsView can then display the selected student's detailed information:

<asp:DetailsView ID="dvStudent"
    runat="server"
    AutoGenerateRows="true">
</asp:DetailsView>

Code-Behind

When the user selects a student, the selected student's ID can be used to retrieve the corresponding record:

protected void gvStudents_SelectedIndexChanged(
    object sender, EventArgs e)
{
    int id = Convert.ToInt32(
        gvStudents.DataKeys[
            gvStudents.SelectedIndex].Value);

    // Fetch student details using id
    // and bind them to dvStudent
}

The basic flow is:

Database
    ↓
GridView (Master)
    ↓
User selects a Student
    ↓
StudentID
    ↓
DetailsView (Detail)
    ↓
Selected Student's Details

Advantages of Master-Detail Binding

  • 01Easy navigation: Users can select a record from a list and immediately view its details.
  • 02Better organization: Large amounts of data can be divided into a summary list and detailed information.
  • 03Improved usability: Users do not need to display all information in one large table.
  • 04Efficient data presentation: The master control shows only important fields while the detail control displays complete information.
Conclusion A Master-Detail relationship connects two data-bound controls so that the Master control determines which record is displayed by the Detail control. For example, a GridView can display a list of students, and selecting one student can display that student's complete information in a DetailsView.
13
5 Marks Question

CSS (Cascading Style Sheets)

CSS (Cascading Style Sheets) is a stylesheet language used to define the appearance and layout of web pages. It controls properties such as colors, fonts, spacing, borders, backgrounds, and positioning of HTML elements.

In ASP.NET, CSS can be used to style both normal HTML elements and ASP.NET server controls through the CssClass property.

Example

CSS file – Site.css:

.header {
    background: #003366;
    color: white;
    text-align: center;
    padding: 15px;
}

.content {
    padding: 20px;
}

Using CSS in an ASP.NET page:

<link href="Site.css" rel="stylesheet" />

For an ASP.NET server control:

<asp:TextBox ID="txtName"
    runat="server"
    CssClass="input-field" />

Here, CssClass="input-field" applies the CSS class to the TextBox.

Types of CSS

1. Inline CSS
Written directly inside an HTML element using the style attribute.
2. Internal CSS
Written inside the <style> tag of an HTML page.
3. External CSS
Written in a separate .css file and linked to the web page.

Advantages of CSS

  • 01Provides a consistent design throughout a website.
  • 02Separates presentation from HTML structure.
  • 03Makes pages easier to maintain.
  • 04Reduces repeated styling code.
  • 05Allows the same stylesheet to be used across multiple pages.

In ASP.NET, linking a CSS file in a Master Page allows all content pages using that Master Page to automatically receive the same styling.

Conclusion CSS is an essential technology for controlling the look, feel, and layout of web applications while keeping styling separate from page content.