0% found this document useful (0 votes)
14 views107 pages

Introduction to ASP.NET Web Forms

The document provides an introduction to ASP.NET and Web Forms, outlining prerequisites, learning objectives, and the agenda for the course. It covers the background of web development technologies, the evolution from ASP to ASP.NET, and key features of ASP.NET, including its programming model and server-side controls. The document emphasizes the benefits of ASP.NET, such as simplified coding, state management, and automatic browser compatibility.

Uploaded by

gowri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views107 pages

Introduction to ASP.NET Web Forms

The document provides an introduction to ASP.NET and Web Forms, outlining prerequisites, learning objectives, and the agenda for the course. It covers the background of web development technologies, the evolution from ASP to ASP.NET, and key features of ASP.NET, including its programming model and server-side controls. The document emphasizes the benefits of ASP.NET, such as simplified coding, state management, and automatic browser compatibility.

Uploaded by

gowri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Introduction to ASP.

NET
and Web Forms

Mark Sapossnek

CS 594
Computer Science Department
Metropolitan College
Boston University
Prerequisites
 This module assumes that you understand the
fundamentals of
 C# programming
 [Link]
 A background in web development (HTML,
JavaScript, DHTML, CGI, Active Server Pages)
would be helpful, but is not required
Learning Objectives
 What is [Link]; why it was developed
 [Link] features
 Programming Web Forms
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Background
Web Architecture

PC/Mac/Unix/...
Client
+ Browser

Request:
[Link]

Network HTTP, TCP/IP

Response:
<html>….</html>

Server Web Server


Background
Web Development Technologies
 Client-side technologies
 HTML, DHTML, JavaScript
 Server-side technologies
 ASP (Active Server Pages)
 [Link] is the next generation of ASP
Background
What is ASP?
 Server-side programming technology
 Consists of static HTML interspersed with script
 ASP intrinsic objects (Request, Response,
Server, Application, Session) provide services
 Commonly uses ADO to interact with databases
 Application and session variables
 Application and session begin/end events
 ASP manages threads, database connections, ...
Background
What is ASP?

HTTP request HTTP response


(form data, HTTP HTML, XML
header data)

ASP page
(static HTML,
server-side logic)
Background
Demo: [Link]

<html>
<head><title>[Link]</title></head>
<body>
<form method=“post">
<input type="submit" id=button1 name=button1
value="Push Me" />
<%
if ([Link]("button1") <> "") then
[Link] "<p>Hello, the time is " & Now()
end if
%>
</form>
</body>
</html>
Background
ASP Successes
 Simple procedural programming model
 Access to COM components
 ActiveX Data Objects (ADO)
 File System Object
 Custom components
 Script-based: no compiling, just edit, save & run
 VBScript, JScript – leverages existing skills
 Support for multiple scripting languages
 ASP has been very popular
Background
ASP Challenges
 Coding overhead (too much code)
 Everything requires writing code!
 Code readability (too complex; code and UI intermingled)
 Maintaining page state requires more code
 Reuse is difficult
 Supporting many types of browsers is difficult
 Deployment issues (e.g. DLL locking)
 Session state scalability and availability
 Limited support for caching, tracing, debugging, etc.
 Performance and safety limitations of script
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
[Link] Overview
 [Link] provides services to allow the
creation, deployment, and execution of
Web Applications and Web Services
 Like ASP, [Link] is a server-side technology
 Web Applications are built using Web Forms
 Web Forms are designed to make building
web-based applications as easy as building
Visual Basic applications
[Link] Overview
Goals
 Keep the good parts of ASP and improve the rest
 Simplify: less code, easier to create and maintain
 Multiple, compiled languages
 Fast
 Scalable
 Manageable
 Available
 Customizable and extensible
 Secure
 Tool support
[Link] Overview
Key Features

 Web Forms  Session management


 Web Services  Caching
 Built on .NET Framework  Debugging
 Simple programming  Extensibility
model  Separation of code and UI
 Maintains page state  Security
 Multibrowser support  ASPX, ASP side by side
 XCOPY deployment  Simplified form validation
 XML configuration  Cookieless sessions
 Complete object model
[Link] Overview
Demo: [Link]
<%@ Page language="c#" %>
<html>
<head></head>
<script runat="server">
public void B_Click (object sender, [Link] e) {
[Link] = "Hello, the time is " + [Link];
}
</script>
<body>
<form method="post" runat="server">
<asp:Button onclick="B_Click" Text="Push Me“
runat="server“ /> <p>
<asp:Label id=Label1 runat="server" />
</form>
</body>
</html>
[Link] Overview
Architecture
 [Link] is built upon
 .NET Framework
 Internet Information Server (IIS)
[Link] Overview
Architecture
 Internet Information Server (IIS)
 IIS MMC Snap-In (Internet Services Manager)
 Tool to manage IIS
 Virtual Directories
 Provides a mapping between URL and file path
 E.g., on my machine the URL:

[Link]
maps to the file path:
C:\_CS594Fall2001
[Link] Overview
Architecture

VB C++ C# JScript …

Visual [Link]
Common Language Specification
[Link]: Web Services Windows
and Web Forms Forms
[Link]: Data and XML
Base Classes
Common Language Runtime
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Programming Model
Controls and Events
 Server-side programming model
 Based on controls and events
 Just like Visual Basic
 Not “data in, HTML out”
 Higher level of abstraction than ASP
 Requires less code
 More modular, readable, and maintainable
Programming Model
Controls and Events

Button code
Button ...

List code
List ...

Text code
Text ...

Browser [Link] Event handlers


Programming Model
[Link] Object Model
 User code executes on the web server in
page or control event handlers
 Controls are objects, available in
server-side code
 Derived from [Link]
 The web page is an object too
 Derived from [Link] which is a
descendant of [Link]
 A page can have methods, properties, etc.
Programming Model
Postbacks
 A postback occurs when a page generates an
HTML form whose values are posted back
to the same page
 A common technique for handling form data
 In ASP and other server-side technologies the
state of the page is lost upon postback...
 Unless you explicitly write code to maintain state
 This is tedious, bulky and error-prone
Programming Model
Postbacks Maintain State
 By default, [Link] maintains the state of all
server-side controls during a postback
 Can use method="post" or method="get"
 Server-side control objects are automatically
populated during postback
 No state stored on server
 Works with all browsers
Programming Model
Server-side Controls
 Multiple sources of controls
 Built-in
 3rd party
 User-defined
 Controls range in complexity and power: button,
text, drop down, calendar, data grid, ad rotator,
validation
 Can be populated via data binding
Programming Model
Automatic Browser Compatibility
 Controls can provide automatic browser
compatibility
 Can target UpLevel or DownLevel browsers
 UpLevel browsers support additional functionality,
such as JavaScript and DHTML
 DownLevel browsers support HTML 3.2
Programming Model
Automatic Browser Compatibility
IE 4
Button

Menu

Text

Netscape Button Control Button code


Button ...
Menu

Text
Menu Control Menu code
...
IE 5.5
Button
Text Control Text code
Menu

Text
...

IE 6
Button

Menu [Link] Event handlers


Text

...
Programming Model
Code-behind pages
 Two styles of creating [Link] pages
 Controls and code in .aspx file
 Controls in .aspx file, code in code-behind page
 Supported in Visual [Link]
 Code-behind pages allow you to separate the
user interface design from the code
 Allows programmers and designers to work
independently
<%@ Codebehind=“[Link]”
Inherits=WebApplication1.WebForm1”
%>
Programming Model
Automatic Compilation
 Just edit the code and hit the page
 [Link] will automatically compile the code
into an assembly
 Compiled code is cached in the CLR
Assembly Cache
 Subsequent page hits use compiled assembly
 If the text of the page changes then the code
is recompiled
 Works just like ASP: edit, save and run
Programming Model
Automatic Compilation
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Programming Basics
Page Syntax
 The most basic page is just static text
 Any HTML page can be renamed .aspx
 Pages may contain:
 Directives: <%@ Page Language=“C#” %>
 Server controls: <asp:Button runat=“server”>
 Code blocks: <script runat=“server”>…</script>
 Data bind expressions: <%# %>
 Server side comments: <%-- --%>
 Render code: <%= %> and <% %>
 Use is discouraged; use <script runat=server> with code in
event handlers instead
Programming Basics
The Page Directive
 Lets you specify page-specific attributes, e.g.
 AspCompat: Compatibility with ASP
 Buffer: Controls page output buffering
 CodePage: Code page for this .aspx page
 ContentType: MIME type of the response
 ErrorPage: URL if unhandled error occurs
 Inherits: Base class of Page object
 Language: Programming language
 Trace: Enables tracing for this page
 Transaction: COM+ transaction setting
 Only one page directive per .aspx file
Programming Basics
Server Control Syntax
 Controls are declared as HTML tags with
runat=“server” attribute
<input type=text id=text2 runat=“server” />
<asp:calendar id=myCal runat=“server” />

 Tag identifies which type of control to create


 Control is implemented as an [Link] class
 The id attribute provides programmatic identifier
 It names the instance available during postback
 Just like Dynamic HTML
Programming Basics
Server Control Properties
 Tag attributes map to control properties
<asp:button id=“c1" Text="Foo" runat=“server”>
<asp:ListBox id=“c2" Rows="5" runat=“server”>

 Tags and attributes are case-insensitive


 Control properties can be set programmatically

[Link] = “Foo”;
[Link] = 5;
Programming Basics
Maintaining State
 By default. controls maintain their state across
multiple postback requests
 Implemented using a hidden HTML field:
__VIEWSTATE
 Works for controls with input data (e.g. TextBox,
CheckBox), non-input controls (e.g. Label,
DataGrid), and hybrids (e.g. DropDownList,
ListBox)
 Can be disabled per control or entire page
 Set EnableViewState=“false”
 Lets you minimize size of __VIEWSTATE
Programming Basics
Maintaining State
 Demo: [Link],
[Link]
Programming Basics
Server Code Blocks
 Server code lives in a script block marked
runat=“server”
<script language="C#" runat=server>
<script language="VB" runat=server>
<script language="JScript" runat=server>

 Script blocks can contain


 Variables, methods, event handlers, properties
 They become members of a custom Page object
Programming Basics
Page Events
 Pages are structured using events
 Enables clean code organization
 Avoids the “Monster IF” statement
 Less complex than ASP pages
 Code can respond to page events
 e.g. Page_Load, Page_Unload
 Code can respond to control events
 Button1_Click
 Textbox1_Changed
Programming Basics
Page Event Lifecycle

Initialize Page_Init
Restore Control State
Load Page Page_Load

Control Events
1. Change Events Textbox1_Changed

2. Action Events Button1_Click

Save Control State


Render
Unload Page Page_Unload
Programming Basics
Page Loading
 Page_Load fires at beginning of request after
controls are initialized
 Input control values already populated

protected void Page_Load(Object s, EventArgs e) {


[Link] = [Link];
}
Programming Basics
Page Loading
 Page_Load fires on every request
 Use [Link] to execute conditional logic
 If a Page/Control is maintaining state then need only
initialize it when IsPostBack is false

protected void Page_Load(Object s, EventArgs e) {


if (! [Link]) {
// Executes only on initial page load
[Link] = "initial value";
}
// Rest of procedure executes on every request
}
Programming Basics
Server Control Events
 Change Events
 By default, these execute only on next action event
 E.g. OnTextChanged, OnCheckedChanged
 Change events fire in random order
 Action Events
 Cause an immediate postback to server
 E.g. OnClick
 Works with any browser
 No client script required, no applets,
no ActiveX® Controls!
Programming Basics
Wiring Up Control Events
 Control event handlers are identified on the tag
<asp:button onclick="btn1_click“ runat=server>
<asp:textbox onchanged="text1_changed“ runat=server>

 Event handler code


protected void btn1_Click(Object s, EventArgs e) {
[Link] = “Button1 clicked”;
}
Programming Basics
Event Arguments
 Events pass two arguments:
 The sender, declared as type object
 Usually the object representing the control that generated
the event
 Allows you to use the same event handler for

multiple controls
 Arguments, declared as type EventArgs
 Provides additional data specific to the event
 EventArgs itself contains no data; a class derived from

EventArgs will be passed


Programming Basics
Page Unloading
 Page_Unload fires after the page is rendered
 Don’t try to add to output
 Useful for logging and clean up

protected void Page_Unload(Object s, EventArgs e) {


[Link]();
}
Programming Basics
Import Directive
 Adds code namespace reference to page
 Avoids having to fully qualify .NET types and
class names
 Equivalent to the C# using directive

<%@ Import Namespace="[Link]" %>


<%@ Import Namespace="[Link]" %>
<%@ Import Namespace="[Link]" %>
Programming Basics
Page Class
 The Page object is always available when
handling server-side events
 Provides a large set of useful properties and
methods, including:
 Application, Cache, Controls,
EnableViewState, EnableViewStateMac,
ErrorPage, IsPostBack, IsValid, Request,
Response, Server, Session, Trace, User,
Validators
 DataBind(), LoadControl(), MapPath(),
Validate()
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Server Controls
 [Link] ships with ~50 built-in controls
 Organized into logical families
 HTML controls
 Controls / properties map 1:1 with HTML
 Web controls
 Richer functionality
 More consistent object model
Server Controls
HTML Controls
 Work well with existing HTML designers
 Properties map 1:1 with HTML
[Link] ="red“;
 Can specify client-side event handlers
 Good when quickly converting existing pages
 Derived from
[Link]
 Supported controls have custom class,
others derive from HtmlGenericControl
Server Controls
HTML Controls
 Supported controls
 <a>
 <textarea>
 <img>
 <button>
 <form>
 <input type=text>
 <table>
 <input type=file>
 <tr>
 <input type=submit>
 <td>
 <input type=button>
 <th>
 <input type=reset>
 <select>
 <input type=hidden>
Server Controls
HTML Controls
 Demo 1: [Link]
 Basic page lifecycle with HTML Controls
 Demo 2: [Link]
 More HTML Controls
Server Controls
HTML Controls
 Can use controls two ways:
 Handle everything in action events (e.g. button click)
 Event code will read the values of other controls (e.g. text,
check boxes, radio buttons, select lists)
 Handle change events as well as action events
Server Controls
Web Controls
 Consistent object model
[Link] = [Link];
[Link] = [Link];

 Richer functionality
 E.g. AutoPostBack, additional methods
 Automatic uplevel/downlevel support
 E.g. validation controls
 Strongly-typed; no generic control
 Enables better compiler type checking
Server Controls
Web Controls
 Web controls appear in HTML markup as
namespaced tags
 Web controls have an asp: prefix
<asp:button onclick="button1_click“ runat=server>
<asp:textbox onchanged="text1_changed“ runat=server>

 Defined in the [Link]


namespace
 This namespace is automatically mapped to the
asp: prefix
Server Controls
Web Controls
 Web Controls provide extensive properties to
control display and format, e.g.
 Font
 BackColor, ForeColor
 BorderColor, BorderStyle, BorderWidth
 Style, CssClass
 Height, Width
 Visible, Enabled
Server Controls
Web Controls
 Four types of Web Controls
 Intrinsic controls
 List controls
 Rich controls
 Validation controls
Server Controls
Intrinisic Controls
 Correspond to HTML controls
 Supported controls
 <asp:button>  <asp:radiobutton>
 <asp:imagebutton>  <asp:image>
 <asp:linkbutton>  <asp:label>
 <asp:hyperlink>  <asp:panel>
 <asp:textbox>  <asp:table>
 <asp:checkbox>
Server Controls
Intrinisic Controls
 TextBox, ListControl, CheckBox and their
subclasses don’t automatically do a postback
when their controls are changed
 Specify AutoPostBack=true to make change
events cause a postback
Server Controls
List Controls
 Controls that handle repetition
 Supported controls
 <asp:dropdownlist>
 <asp:listbox>
 <asp:radiobuttonlist>
 <asp:checkboxlist>
 <asp:repeater>
 <asp:datalist>
 <asp:datagrid>
Server Controls
List Controls
 Repeater, DataList and DataGrid controls
 Powerful, customizable list controls
 Expose templates for customization
 Can contain other controls
 Provide event bubbling through their
OnItemCommand event
 More about these controls and templates later
Server Controls
CheckBoxList & RadioButtonList
 Provides a collection of check box or
radio button controls
 Can be populated via data binding
<asp:CheckBoxList id=Check1 runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
</asp:CheckBoxList>
Server Controls
Intrinisic & Simple List Controls
 Demo 1: [Link]
 Assorted intrinsic and list controls
 Demo 2: [Link]
 Same controls with AutoPostBack
Server Controls
Rich Controls
 Custom controls with rich functionality
 Supported Controls
 <asp:calendar>
 <asp:adrotator>
 More will be added
 3rd party controls are coming
 Demo: [Link]
Server Controls
Validation Controls
 Rich, declarative validation
 Validation declared separately from input control
 Extensible validation framework
 Supports validation on client and server
 Automatically detects uplevel clients
 Avoids roundtrips for uplevel clients
 Server-side validation is always done
 Prevents users from spoofing Web Forms
Server Controls
Validation Controls
 <asp:RequiredFieldValidator>
 Ensures that a value is entered
 <asp:RangeValidator>
 Checks if value is within minimum and maximum values
 <asp:CompareValidator>
 Compares value against constant, another control or data type
 <asp:RegularExpressionValidator>
 Tests if value matches a predefined pattern
 <asp:CustomValidator>
 Lets you create custom client- or server-side validation function
 <asp:ValidationSummary>
 Displays list of validation errors in one place
Server Controls
Validation Controls
 Validation controls are derived from
[Link],
which is derived from the Label control
 Validation controls contain text which is displayed
only if validation fails
 Text property is displayed at control location
 ErrorMessage is displayed in summary
Server Controls
Validation Controls
 Validation controls are associated with their
target control using the ControlToValidate
property

<asp:TextBox id=TextBox1 runat=server />

<asp:RequiredFieldValidator id="Req1"

ControlToValidate="TextBox1"
Text="Required Field" runat=server />

 Can create multiple validation controls with the


same target control
Server Controls
Validation Controls
 [Link] indicates if all validation
controls on the page succeed

void Submit_click(object s, EventArgs e) {


if ([Link]) {
[Link] = "Page is valid!";
}
}
Server Controls
Validation Controls
 Display property controls layout
 Static: fixed layout, display won’t change if invalid
 Dynamic: dynamic layout
 None: no display; can still use ValidationSummary
and [Link]
 Type property specifies expected data type:
Currency, Date, Double, Integer, String
Server Controls
Validation Controls
 Can force down-level option
 Only server-side validation

<% @ Page Language="c#"


ClientTarget="DownLevel" %>
Server Controls
Validation Controls
 Demo: [Link]
 Demonstrates each type of validation control
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Data Binding
How to Populate Server Controls?
 Specify the data in the control’s tags
 Not dynamic: can’t get data from a database
 Write code that uses the control’s object model
 This is okay if you need to populate a simple value or
list, but quickly gets too complicated for populating
sophisticated displays
 Data binding
 Create an object that holds the data
(DataSet, Array, string, int, etc.)
 Associate that object with the control
Data Binding
What Is It?
 Provides a single simple yet powerful way to
populate Web Form controls with data
 Enables clean separation of code from UI
 Supports binding to any data source
 Properties, expressions, method calls
 Collections (Array, Hashtable, etc.)
 DataSet, DataTable, DataView, DataReader
 XML
 One way snapshot model
 Requires code to reapply to data model
Data Binding
What Is It?
 Allows you to specify an expression
 When the DataBind method of the control is
called, the expression is evaluated and bound
 DataBind for a single control (and subcontrols)
 [Link] binds all controls on a page
 Works for scalars, e.g. Label control
 Works for lists, e.g. DropDown control,
ListBox control, etc.
 Enables the use of templates
Data Binding
Scalar Expressions
 Data binding expression: <%# expression %>
 Expression is evaluated when DataBind()
is called
<asp:Label id=label1
Text=<%# “The result is “ + (1 + 2) +
“, the time is “ + [Link]() %>
runat="server" />

public void Page_Load(object s, EventArgs e) {


if (! [Link])
[Link]();
}
Data Binding
Scalar Expressions
 Demo: [Link]
 Data binding to simple, scalar expressions
Data Binding
Simple Lists
 Data binding a list creates a user interface
element for each item in the list
 Each item contains text (displayed to user) and
an optional value (not displayed)
 The simple list controls:
 <asp:ListBox>
 Single or multiple select
 <asp:DropDownList>
 <asp:RadioButtonList>
 <asp:CheckBoxList>
Data Binding
Simple Lists
 Steps to data bind a list control
 Declare the list control
 Optionally set DataValueField
and DataTextField
 Set its DataSource
 Call DataBind() method
Data Binding
Simple Lists
 Demo: [Link]
 Data binding to simple lists
Data Binding
Database
 Data binding can be used to populate server
controls with data from a database
 Each UI element corresponds to a row
 Bind to a DataReader (preferred)
 Bind to a DataView of a DataSet
 Specify value and text with DataValueField
and DataTextField, respectively
 Each of these corresponds to a column
Data Binding
Data Source Example

DataView GetSampleData() {
DataSet ds;
SqlConnection cxn;
SqlDataAdapter adp;
cxn = new SqlConnection("server=localhost; " +
"uid=sa;pwd=;database=Northwind");
adp = new SqlDataAdapter(
"select CategoryID, CategoryName from
Categories",
cxn);
ds = new DataSet();
[Link](ds, "Categories");
return [Link]["Categories"].DefaultView;
}
Data Binding
List Binding Examples
void Page_Load(object s, EventArgs e) {
[Link] = GetSampleData();
[Link] = "CategoryID";
[Link] = "CategoryName";
[Link]();
}
<asp:ListBox id="ListBox1" runat="server" />

void Page_Load(object s, EventArgs e) {


[Link]();
}
<asp:ListBox id="ListBox1" runat="server"
DataSource=<%# GetSampleData() %>
DataValueField=“CategoryID”
DataTextField=“CategoryName” />
Data Binding
Binding to a Database
 Demo: [Link]
 Data binding to a database
Data Binding
DataGrid
 Full-featured list output
 Default look is a grid
 Default is to show all columns, though you can
specify a subset of columns to display
 Columns can be formatted with templates
 Optional paging
 Updateable
Data Binding
Binding to All Columns
 Binding all columns in the datasource
 Declare an <asp:DataGrid>
 Set its DataSource
 Call DataBind()

void Page_Load(object s, EventArgs e) {


[Link] = GetSampleData();
[Link]();
}

<asp:datagrid id=myDataGrid
runat="server" />
Data Binding
Binding to Specific Columns
 By default, DataGrid will display all columns
 To control columns to display:
 Set AutoGenerateColumns=“false”
 Specify Columns property
 Add column definition
 BoundColumn
 TemplateColumn

 ButtonColumn, EditCommandColumn, HyperlinkColumn


Data Binding
Binding to Specific Columns
 Binding to specific columns in the datasource
 Declare an <asp:DataGrid>
 Declare its Columns collection
 Set its DataSource
 Call its DataBind() method
<asp:datagrid id=myDataGrid
autogeneratecolumns=false runat=server>
<Columns>
<asp:BoundColumn HeaderText=“Id" DataField="title_id" />
<asp:BoundColumn HeaderText="Title“ DataField="title"/>
</Columns>
</asp:datagrid>
Data Binding
DataGrid Paging
 When there is too much data to display in one
screen, a DataGrid can provide automatic
paging
 Set AllowPaging=“true”
 Set PageSize=5
 Handle OnPageIndexChanged event
 Set page index
 Fetch data

 Re-bind data
Data Binding
DataGrid Demo
 Demo: [Link]
 Binding to a database with DataGrid
 Demo: [Link]
 Paging through data with DataGrid
Data Binding
Templates
 Templates provide a powerful way to customize the
display of a server control
 Customize structure – not just style
 Can use controls or other HTML within a template
 3rd party controls can expose new templates
 With data binding, templates specify a set of markup
(HTML or server controls) for each bound piece of data
 Not just specifying formatting and style for a column
 However, templates are not limited to data binding
 No fixed set of templates
 Controls may define their own and expose any number of them
Data Binding
Templates
 Standard templates for list-bound controls
 HeaderTemplate: rendered once before all data
bound rows
 ItemTemplate: rendered once for each row in the
data source
 AlternatingItemTemplate: like ItemTemplate,
but when present is used for every other row
 SeparatorTemplate: rendered between each row
 FooterTemplate: rendered once, after all data
bound rows
Data Binding
Templates

HeaderTemplate
HeaderTemplate Templates
used in
Repeater
ItemTemplate
ItemTemplate controls

SeparatorTemplate
SeparatorTemplate

AlternatingItem-
AlternatingItem-
Template
Template

FooterTemplate
FooterTemplate
Data Binding
Data Binding in Templates
 Templates need to access the bound data
 Container is an alias for the template’s
containing control
 DataItem is an alias for the current row of the
datasource
 [Link] is a utility function provided
to retrieve and format data within a template
<%# [Link]([Link], "price", "$ {0}") %>
Data Binding
Repeater Control
 Provides simple output of a list of items
 No inherent visual form
 Templates provide the visual form
 No paging
 Can provide templates for separators
 Not updateable
Data Binding
Repeater Control
<asp:Repeater id="repList" runat="server">
<template name="HeaderTemplate">
<table>
<tr><td>Title</td><td>Type</td></tr>
</template>

<template name="ItemTemplate">
<tr>
<td><%# [Link]([Link],"title_id") %></td>
<td><%# [Link]([Link],"type") %></td>
</tr>
</template>

<template name="FooterTemplate">
</table>
</template>
</asp:Repeater>
Data Binding
DataList Control
 Provides list output with editing
 Default look is a table
 Customized via templates
 Directional rendering (horizontal or vertical)
 Single and multiple selection
 Alternate item
 Updateable
 No paging
Data Binding
DataList Control

void Page_Load(object s, EventArgs e) {


[Link] = GetSampleData();
[Link]();
}

<asp:datalist id=myDataList runat=server>


<template name="itemtemplate">
<b>Title id:</b>
<%# [Link]([Link], "title_id") %>
<br> <b>Title:</b>
<%# [Link]([Link], "title") %>
</template>
</asp:datalist>
Data Binding
Templates Demo
 Demo: [Link], [Link]
 Using templates and data binding to a database with
DataGrid, Repeater and DataList controls
Agenda
 Background
 [Link] Overview
 Programming Model
 Programming Basics
 Server Controls
 Data Binding
 Conclusion
Conclusion
 We covered
 What [Link] and Web Forms are
 [Link] Programming Essentials
 Server Controls
 Data Binding
 Templates
Conclusion
 Next time, we’ll cover
 Web Applications
 Configuration
 Tracing
 Session Management
 Error Handling
 Deployment
 Security
 Architecture
 Extensibility (User Controls and Custom Controls)
Resources
 General Sites
 [Link]
 [Link]
 [Link]
[Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
Resources
 [Link] Overview
[Link]
[Link]
 Validation
[Link]
tm
 Databinding in 3 parts
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
 [Link] component model
[Link]
[Link]

You might also like